Topic Portal
Problem-solving ideas:
With eight queens is very similar, except that this question without recording a slash, but to record each grids, should fill the number in each position.
AC Code:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstdlib> 4 5 using namespace std; 6 7 int a[10][10]; 8 bool h[10][10],l[10][10],g[10][10]; 9 10 inline void print() { 11 for(int i = 1;i <= 9; i++) { 12 for(int j = 1;j <= 9; j++) 13 printf("%d ",a[i][j]); 14 printf("\n"); 15 } 16 exit(0); 17 } 18 19 inline void dfs(int x,int y) { 20 if(a[x][y] != 0) { 21 if(x == 9 && y == 9) 22 print(); 23 else 24 if(y == 9) 25 dfs(x + 1,1); 26 else 27 dfs(x,y + 1); 28 } 29 if(a[x][y] == 0) { 30 for(int i = 1;i <= 9; i++) { 31 if(!h[i][x] && !l[i][y] && !g[i][(x-1)/3*3+(y-1)/3+1]) { 32 a[x][y] = i; 33 h[i][x] = 1; 34 l[i][y] = 1; 35 g[i][(x-1)/3*3+(y-1)/3+1] = 1; 36 if(x == 9 && y == 9) 37 print(); 38 if(y == 9) 39 dfs(x + 1,1); 40 else 41 dfs(x,y + 1); 42 a[x][y] = 0; 43 h[i][x] = 0; 44 l[i][y] = 0; 45 g[i][(x-1)/3*3+(y-1)/3+1] = 0; 46 } 47 } 48 } 49 } 50 51 int main() 52 { 53 for(int i = 1;i <= 9; i++) 54 for(int j = 1;j <= 9; j++){ 55 scanf("%d",&a[i][j]); 56 h[a[i][j]][i] = l[a[i][j]][j] = g[a[i][j]][(i-1)/3*3+(j-1)/3+1] = 1; 57 } 58 dfs(1,1); 59 return 0; 60 }