DFS:解数独
作者:互联网
//code:
#include<cstdio>
#define rep(i,a,b) for(int i=a;i<b;i++)
bool row[10][10], col[10][10], box[10][10];
int grid[10][10];
bool flag = 0;
void dfs(int n) {
if (n > 80) {
flag = 1;
rep(i, 0, 9) {
rep(j, 0, 9)
printf("%d ", grid[i][j]);
printf("\n");
}
return;
}
if (!flag) {
int x = n / 9, y = n % 9, t = y / 3 + x / 3 * 3;
if (!grid[x][y]) {
rep(i, 1, 10) {
if (!row[x][i] && !col[y][i] && !box[t][i]) {
grid[x][y] = i;
row[x][i] = 1;
col[y][i] = 1;
box[t][i] = 1;
dfs(n + 1);
grid[x][y] = 0;
row[x][i] = 0;
col[y][i] = 0;
box[t][i] = 0;
}
}
}
else dfs(n + 1);
}
}
int main() {
rep(i, 0, 9)rep(j, 0, 9) {
scanf("%d", &grid[i][j]);
int t = j / 3 + i / 3 * 3;
if (grid[i][j]) {
row[i][grid[i][j]] = 1;
col[j][grid[i][j]] = 1;
box[t][grid[i][j]] = 1;
}
}
dfs(0);
}
关键用整数除模运算建立第n格到row,col,box的映射,通过row[i][k]记录第i行数k有没有填过,col与box的bool数组同理.(开二维数组trade-memory trade-off,比每次调用判断函数循环进行行列宫判断要快.)
标签:box,10,int,DFS,grid,解数,col,row 来源: https://www.cnblogs.com/dwt2021/p/14254062.html