一列一列的放 判断是否符合条件
View Code
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 char s[20][20]; 7 int vx[20][20],vy[20][20],vis[20][20]; 8 int judge(int x,int y) 9 { 10 if(x>=0&&x<3&&y>=0&&y<3) 11 return 1; 12 if(x>=0&&x<3&&y>=3&&y<6) 13 return 2; 14 if(x>=0&&x<3&&y>=6&&y<9) 15 return 3; 16 if(x>=3&&x<6&&y>=0&&y<3) 17 return 4; 18 if(x>=3&&x<6&&y>=3&&y<6) 19 return 5; 20 if(x>=3&&x<6&&y>=6&&y<9) 21 return 6; 22 if(x>=6&&x<9&&y>=0&&y<3) 23 return 7; 24 if(x>=6&&x<9&&y>=3&&y<6) 25 return 8; 26 if(x>=6&&x<9&&y>=6&&y<9) 27 return 9; 28 } 29 int dfs(int x,int y) 30 { 31 int kk=0,k; 32 if(x==9) 33 return 1; 34 if(s[x][y]!='0') 35 { 36 if(y==8) 37 kk = dfs(x+1,0); 38 else 39 kk = dfs(x,y+1); 40 if(kk) 41 return 1; 42 else 43 return 0; 44 } 45 else 46 { 47 for(k = 1; k <= 9 ; k++) 48 { 49 if(!vx[x][k]&&!vy[y][k]&&!vis[judge(x,y)][k]) 50 { 51 vx[x][k] = 1; 52 vy[y][k] = 1; 53 vis[judge(x,y)][k] = 1; 54 s[x][y] = k+'0'; 55 if(y==8) 56 kk = dfs(x+1,0); 57 else 58 kk = dfs(x,y+1); 59 if(kk) 60 return 1; 61 else 62 { 63 s[x][y] = '0'; 64 vx[x][k] = 0; 65 vy[y][k] = 0; 66 vis[judge(x,y)][k] = 0; 67 } 68 } 69 } 70 } 71 return 0; 72 } 73 int main() 74 { 75 int i,j,t; 76 cin>>t; 77 while(t--) 78 { 79 memset(vx,0,sizeof(vx)); 80 memset(vy,0,sizeof(vy)); 81 memset(vis,0,sizeof(vis)); 82 getchar(); 83 for(i = 0 ; i < 9 ; i++) 84 for(j = 0 ; j < 9 ; j++) 85 { 86 cin>>s[i][j]; 87 if(s[i][j]!='0') 88 { 89 vx[i][s[i][j]-'0'] = 1; 90 vy[j][s[i][j]-'0'] = 1; 91 vis[judge(i,j)][s[i][j]-'0'] = 1; 92 } 93 } 94 if(dfs(0,0)) 95 { 96 for(i = 0 ; i < 9 ; i++) 97 { 98 for(j = 0 ; j < 9 ;j++) 99 cout<