https://www.luogu.org/problemnew/show/P1784
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int a[10][10], row[10][10],col[10][10], re[10][10];
//分别记录数独,标记行 标记列 标记宫格对应的数字是否已经用了
void print()
{
for(int i = 1; i <= 9; i++)
{
for(int j = 1; j <=9; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
exit(0);
//system("pause");
}
void dfs(int x, int y)
{
if(a[x][y])//如果这个空格本来填了
{
if(x == 9 && y == 9)//填完了
{
print();
}
else if(y == 9)//还没有填完但是这一行填完了
dfs(x + 1, 1);//填下一行
else
dfs(x, y + 1);//填下一列
}
else
{
for(int i = 1; i <=9; i++)
{
if(!row[x][i] && !col[y][i] && !re[(x-1)/3*3 + (y-1)/3 + 1][i])
{
//如果i在第x行和y列和该宫格没右出现过
a[x][y] = i;//填
//标记已用这一列和行和宫格
row[x][i] = 1;
col[y][i] = 1;
re[(x-1)/3*3 + (y-1)/3 + 1][i] = 1;
if(x == 9 && y == 9)//填完
{
print();
}
else if(y == 9)//填下一行
dfs(x + 1, 1);
else
dfs(x, y + 1);//填下一列
//回溯
a[x][y] = 0;
row[x][i] = 0;
col[y][i] = 0;
re[(x-1)/3*3 + (y-1)/3 + 1][i] = 0;
}
}
}
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
for(int i = 1; i <= 9; i++)
{
for(int j = 1; j <= 9; j++)
{
cin>>a[i][j];
if(a[i][j])
{
row[i][a[i][j]] = 1;
col[j][a[i][j]] = 1;
re[(i-1)/3*3 + (j-1)/3 + 1][a[i][j]] = 1;
}
}
}
//cout<<endl;
dfs(1,1);
system("pause");
}