标签:
1 #include<cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<cstdlib> 5 #include<vector> 6 #include<queue> 7 #include<stack> 8 #include<bitset> 9 #include<iomanip> 10 #include<algorithm> 11 #include<string> 12 #include<cstring> 13 #define inf 100000 14 using namespace std; 15 int t[15][15]; 16 bool area[15][15],hang[15][15],lie[15][15]; 17 int x,cnt; 18 void dfs(){ 19 int cnt=inf,x,y; 20 for (int i=1;i<=9;i++) 21 for (int j=1;j<=9;j++) 22 if(t[i][j]==0) 23 { 24 int cntt=0; 25 for (int k=1;k<=9;k++) 26 if (!hang[i][k]&&!lie[j][k]&&!area[((i+2)/3-1)*3+(j+2)/3][k]) 27 cntt++; 28 if (cnt>cntt) 29 { 30 x=i; 31 y=j; 32 cnt=cntt; 33 } 34 } 35 if (cnt==inf) 36 { 37 for (int i=1;i<=9;i++) 38 { 39 for (int j=1;j<=9;j++) 40 { 41 printf ("%d ",t[i][j]); 42 } 43 printf ("\n"); 44 } 45 exit(0);//here 46 } 47 for (int k=1;k<=9;k++) 48 if (!hang[x][k]&&!lie[y][k]&&!area[((x+2)/3-1)*3+(y+2)/3][k]) 49 { 50 hang[x][k]=true; 51 lie[y][k]=true; 52 area[((x+2)/3-1)*3+(y+2)/3][k]=true; 53 t[x][y]=k; 54 dfs(); 55 hang[x][k]=false; 56 lie[y][k]=false; 57 area[((x+2)/3-1)*3+(y+2)/3][k]=false; 58 t[x][y]=0; 59 } 60 } 61 int main (){ 62 freopen ("sudoku.in","r",stdin); 63 //freopen ("sudoku.out","w",stdout); 64 for (int i=1;i<=9;i++) 65 for (int j=1;j<=9;j++) 66 { 67 scanf ("%d",&t[i][j]); 68 hang[i][t[i][j]]=true; 69 lie[j][t[i][j]]=true; 70 area[((i+2)/3-1)*3+(j+2)/3][t[i][j]]=true; 71 } 72 dfs(); 73 return 0; 74 }
标签:
原文地址:http://www.cnblogs.com/Ang-Eric/p/5782827.html