Sudoku POJ - 2676
问题
我是抄的这篇题解传送门.
代码
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
bool square[9][10],checkcol[9][10],checkrow[9][10];
int sudoku[9][9];
bool isdone;
void dfs(int i,int j)
{
if(i==9)
{
isdone = true;
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
cout << sudoku[i][j];
}
cout << "
";
}
return ;
}
if(isdone)
return ;
if(sudoku[i][j])
{
if(j==8)
dfs(i+1,0);
else
dfs(i,j+1);
}
else
{
for(int num=1;num<10;num++)
{
int k = 3*(i/3) + j/3;
if(!checkrow[i][num] && !checkcol[j][num] &&!square[k][num])
{
sudoku[i][j] = num;
checkrow[i][num] = checkcol[j][num] = square[k][num] = true;
if(j==8)
dfs(i+1,0);
else
dfs(i,j+1);
sudoku[i][j] = 0;
checkrow[i][num] = checkcol[j][num] = square[k][num] = false;
}
}
}
}
int main() {
int t;
cin >> t;
while(t--)
{
memset(square,0, sizeof(square));
memset(checkcol,0,sizeof(checkcol));
memset(checkrow,0,sizeof(checkrow));
for(int i=0;i<9;i++)
{
char tmp[9];
cin >> tmp;
for(int j=0;j<9;j++)
{
sudoku[i][j] = tmp[j] - '0';
if(sudoku[i][j])
{
int k = 3*(i/3) + j/3;
checkrow[i][sudoku[i][j]] = 1;
checkcol[j][sudoku[i][j]] = 1;
square[k][sudoku[i][j]] = 1;
}
}
}
isdone = false;
dfs(0,0);
}
return 0;
}