思路:
dfs即可,赋值前先判断是否可以
#include <bits/stdc++.h>
using namespace std;
struct point
{
int x, y;
}p[81];
int num, flag, G[10][10];
int judge(int n, int k)
{
int i, j, x, y;
for(i = 0; i < 9; i++)//所在行列是否重复
{
if(i != p[n].y && G[p[n].x][i] == k)
return 0;
if(i != p[n].x && G[i][p[n].y] == k)
return 0;
}
x = p[n].x / 3 * 3;//神来之笔
y = p[n].y / 3 * 3;
for(i = 0; i < 3; i++) //3*3 是否重复
for(j = 0; j < 3; j++)
if(G[x+i][y+j] == k && !(i == p[n].x && j == p[n].y))
return 0;
return 1;
}
void dfs(int n)
{
int i;
if(n == num)
{
flag = 1;
return;
}
for(i = 1; i < 10; i++)
{
if(judge(n, i))
{
G[p[n].x][p[n].y] = i;
dfs(n + 1);
if(flag)
return;
G[p[n].x][p[n].y] = 0;
}
}
return;
}
int main()
{
int i, j, t = 0;
char s[2];
while(scanf("%s", s) != -1)
{
num = flag = 0;
if(s[0] == '?')
p[num].x = 0, p[num++].y = 0, G[0][0] = 0;
else
G[0][0] = s[0] - '0';
for(i = 0; i < 9; i++)
for(j = 0; j < 9; j++)
if(i || j)
{
scanf("%s", s);
if(s[0] == '?')
p[num].x = i, p[num++].y = j, G[i][j] = 0;
else
G[i][j] = s[0] - '0';
}
dfs(0);
if(t++)
printf("\n");
for(i = 0; i < 9; i++)
{
for(j = 0; j < 8; j++)
printf("%d ", G[i][j]);
printf("%d\n", G[i][8]);
}
}
return 0;
}