直接dfs就可以了。
参考了别人了。不过写起来不难。
/*
POJ: 2676 Sudoku
*/
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
using namespace std;
int map[10][10];
bool row[10][10];
bool column[10][10];
bool grid[10][10];
bool dfs(int x, int y)
{
if(x >= 9)
return true;
if(map[x][y] > 0) {
bool flag = false;
if(y < 8)
flag = dfs(x, y + 1);
else
flag = dfs(x + 1, 0);
return flag;
}
else {
int z = 3 * (x / 3) + (y / 3);
for(int i = 1; i <= 9; i++) {
if(!row[x][i] && !column[y][i] && !grid[z][i]) {
bool flag = false;
map[x][y] = i;
row[x][i] = true;
column[y][i] = true;
grid[z][i] = true;
if(y < 8)
flag = dfs(x, y + 1);
else
flag = dfs(x + 1, 0);
if(!flag) {
row[x][i] = false;
column[y][i] = false;
grid[z][i] = false;
map[x][y] = 0;
}
else
return true;
}
}
}
return false;
}
int main()
{
//freopen("data.in", "rb", stdin);
int t;
scanf("%d", &t);
while(t--) {
memset(row, false, sizeof(row));
memset(column, false, sizeof(column));
memset(grid, false, sizeof(grid));
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++) {
char ch;
while(ch = getchar()) {
if(ch <= '9' && ch >= '0')
break;
}
map[i][j] = ch - '0';
if(map[i][j] > 0) {
row[i][map[i][j]] = true;
column[j][map[i][j]] = true;
grid[3 * (i / 3) + j / 3][map[i][j]] = true;
}
}
dfs(0, 0);
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++)
printf("%d", map[i][j]);
printf("\n");
}
}
return 0;
}