题意:
解决数独问题
思路:
DFS + 剪枝(构造数组)
反思:
1、没有想到运用构造数组的方法来剪枝;
2、没有掌握回溯法,即当解空间子树都无法解决问题时,根节点要清零。
实现:
#include <iostream>
#include <cstring>
#define clr(x) memset(x, 0, sizeof(x))
using namespace std;
int grid[9][9];
bool row[9][10], col[9][10], sqr[9][10];
bool DFS(int x, int y)
{
if(x == 9) return true;
if(grid[x][y])
{
if(y == 8) return DFS(x + 1, 0);
else return DFS(x, y + 1);
}
else
{
for(int i = 1; i <= 9; i++)
{
if(!row[x][i] && !col[y][i] && !sqr[3*(x/3) + y/3][i])
{
grid[x][y] = i;
row[x][i] = true; col[y][i] = true; sqr[3*(x/3) + y/3][i] = true;
if(y == 8)
{
if(DFS(x + 1, 0)) return true;
else
{
grid[x][y] = 0;
row[x][i] = false; col[y][i] = false; sqr[3*(x/3) + y/3][i] = false;
}
}
else
{
if(DFS(x, y + 1)) return true;
else
{
grid[x][y] = 0;
row[x][i] = false; col[y][i] = false; sqr[3*(x/3) + y/3][i] = false;
}
}
}
}
return false;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int t; cin >> t;
while(t--)
{
clr(row); clr(col); clr(sqr);
char temp[9][9];
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
cin >> temp[i][j];
grid[i][j] = temp[i][j] - '0';
row[i][ grid[i][j] ] = true;
col[j][ grid[i][j] ] = true;
sqr[3*(i/3) + j/3][ grid[i][j] ] = true;
}
}
DFS(0, 0);
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
cout << grid[i][j];
}
cout << endl;
}
}
}