POJ_2676 Sudoku(DFS)
写了整整一天,到晚上才出过样例,然后各种wa, tle ,ole !!!
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 11;
char map[N][N];
int hr[N][N];
int hc[N][N];
int hx[3][3][N];
int z;
void dfs(int i, int j){
int x, y, k, l;
if( i < 0 && z){
for(k = 0; k < 9; k++){
for(l = 0; l < 9; l++){
printf("%c", map[k][l]);
}
printf("\n");
}
z = 0;
return ;
}
if(map[i][j] != '0' && z){
x = i;
y = j - 1;
if(y < 0){
y = 8; x = i-1;
}
dfs(x, y);
} else {
for(k = 1; k <= 9 && z; k++){
if(!hr[i][k] && !hc[j][k] && !hx[i/3][j/3][k]){
hr[i][k] = hc[j][k] = hx[i/3][j/3][k] = 1;
map[i][j] = k + '0';
x = i; y = j-1;
if(y < 0){
y = 8; x = i-1;
}
//cout << x << ' ' << y << endl;
dfs(x, y);
hr[i][k] = hc[j][k] = hx[i/3][j/3][k] = 0;
map[i][j] = '0';
}
}
}
}
int main(){
//freopen("data.in", "r", stdin);
int t, i, j;
scanf("%d", &t);
while(t--){
char s[10];
for(i = 0; i < 9; i++){
scanf("%s", s);
for(j = 0; j < 9; j++){
map[i][j] = s[j];
}
}
memset(hr, 0, sizeof(hr));
memset(hc, 0, sizeof(hc));
memset(hx, 0, sizeof(hx));
for(i = 0; i < 9; i++){
for(j = 0; j < 9; j++){
if(map[i][j] != '0'){
hr[i][map[i][j]-'0'] = 1;
hx[i/3][j/3][map[i][j]-'0'] = 1;
}
}
}
for(j = 0; j < 9; j++){
for(i = 0; i < 9; i++)
if(map[i][j] != '0')
hc[j][map[i][j]-'0'] = 1;
}z = 1;
dfs(8, 8);
}
return 0;
}