简单粗暴的深搜。
#include <iostream>
#include <cstdio>
#include <vector>
#include <cctype>
using namespace std;
const int N = 9;
int board[N][N];
struct Point
{
int r;
int c;
Point(int r=0, int c=0)
{
this->r = r;
this->c = c;
}
};
vector<Point>pot;
void read_board()
{
int ch;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
{
while (!isdigit(ch=getchar()))
;
board[i][j] = ch - '0';
}
}
int init_empty()
{
pot.clear();
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
{
if (!board[i][j])
pot.push_back(Point(i, j));
}
return pot.size();
}
bool is_ok(int x, int r, int c)
{
for (int i = 0; i < N; i++)
if (board[r][i] == x || board[i][c] == x)
return false;
r = r / 3 * 3;
c = c / 3 * 3;
for (int i = r; i < r + 3; i++)
for (int j = c; j < c + 3; j++)
{
if (board[i][j] == x)
return false;
}
return true;
}
bool fill_empty(int cnt, int tot)
{
if (cnt >= tot)
return true;
int r = pot[cnt].r;
int c = pot[cnt].c;
for (int i = 1; i <= N; i++)
{
if (is_ok(i, r, c))
{
board[r][c] = i;
if(fill_empty(cnt+1, tot))
return true;
board[r][c] = 0;
}
}
return false;
}
void print_board()
{
for (int i = 0; i < N; i++)
{
putchar('\n');
for (int j = 0 ; j < N; j++)
printf("%d", board[i][j]);
}
}
int main()
{
int T;
int tot;
scanf("%d", &T);
while (T-- > 0)
{
read_board();
tot = init_empty();
fill_empty(0, tot);
print_board();
}
return 0;
}