POJ 2676 Suduku
先直接贴代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 15;
int p[N][N];
bool row[N][N];
bool col[N][N];//column
bool nine[N][N];
int temp;
int temp1;
// int k1 ;//When initial the variable k1 here, wa.Wht is that???
void init()
{
memset(row, false, sizeof(row));
memset(col, false, sizeof(col));
memset(nine, false, sizeof(nine));
}
void input()
{
for(int i = 0 ; i < 9 ; i++)
for(int j = 0 ; j < 9 ; j++)
{
scanf("%1d",&p[i][j]);
if(p[i][j])
{
temp = p[i][j];
row[i][temp] = true;
col[j][temp] = true;
temp1 = (i / 3)*3 + j / 3 ;
nine[temp1][temp] = true;
}
}
}
bool dfs(int x,int y)
{
if(x==9) return true;
bool flag=false;
if(p[x][y])
{
if(y==8) flag=dfs(x+1,0);
else flag=dfs(x,y+1);
return flag;
}
int k1 = (x / 3)*3 + y / 3 ;
for(int i=1;i<=9;i++) if(!row[x][i] && !col[y][i] && !nine[k1][i])
{
p[x][y] = i;
row[x][i] = true;
col[y][i] = true;
nine[k1][i] = true;
if(y==8) flag=dfs(x+1,0);
else flag=dfs(x,y+1);
if(flag) return true;
p[x][y] = 0;
row[x][i] = false;
col[y][i] = false;
nine[k1][i] = false;
}
return false;
}
int main()
{
int T;
cin >> T;
while(T--)
{
init();
input();
dfs(0,0);
for(int i = 0 ; i < 9 ; i++)
for(int j = 0 ; j < 9 ; j++)
{
cout << p[i][j];
if( j == 8 ) cout << endl;
}
}
return 0;
}