Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6884 Accepted Submission(s): 2142
1 //刚开始想从map中依次找是?的但超时 2 //可以先把是?的先存起来,dfs时枚举就行 3 #include<iostream> 4 #include<cstdio> 5 #include<cstring> 6 using namespace std; 7 int map[11][11]; 8 int mx[90],my[90]; 9 int cnt,n; 10 int hag(int x,int c) 11 { 12 for(int i=1;i<=9;i++) 13 if(map[x][i]==c) 14 return 1; 15 return 0; 16 } 17 int lie(int y,int c) 18 { 19 for(int i=1;i<=9;i++) 20 if(map[i][y]==c) 21 return 1; 22 return 0; 23 } 24 int kua(int x,int y,int c) 25 { 26 int a=(x-1)/3,b=(y-1)/3; 27 for(int i=a*3+1;i<=(a+1)*3;i++) 28 for(int j=b*3+1;j<=(b+1)*3;j++) 29 if(map[i][j]==c) 30 return 1; 31 return 0; 32 } 33 void dfs(int p) 34 { 35 if(cnt==n) 36 return; 37 for(int i=1;i<=9;i++) 38 { 39 if(hag(mx[p],i)) continue; 40 if(lie(my[p],i)) continue; 41 if(kua(mx[p],my[p],i)) continue; 42 map[mx[p]][my[p]]=i; 43 cnt++; 44 dfs(p+1); 45 if(cnt==n) 46 return; 47 map[mx[p]][my[p]]=0; 48 cnt--; 49 } 50 } 51 int main() 52 { 53 char ch[2]; 54 int h=0; 55 while(scanf("%s",ch)!=EOF) 56 { 57 h++; 58 n=0; 59 if(ch[0]==‘?‘) { 60 map[1][1]=0; 61 mx[n]=1;my[n]=1; 62 n++; 63 } 64 else map[1][1]=ch[0]-‘0‘; 65 for(int i=1;i<=9;i++) 66 { 67 for(int j=1;j<=9;j++) 68 { 69 if(i==1&&j==1) continue; 70 scanf("%s",ch); 71 if(ch[0]==‘?‘) { 72 map[i][j]=0; 73 mx[n]=i;my[n]=j; 74 n++; 75 } 76 else map[i][j]=ch[0]-‘0‘; 77 } 78 } 79 cnt=0; 80 dfs(0); 81 if(h>1) printf("\n"); 82 for(int i=1;i<=9;i++) 83 { 84 for(int j=1;j<=8;j++) 85 { 86 printf("%d ",map[i][j]); 87 } 88 printf("%d\n",map[i][9]); 89 } 90 91 } 92 return 0; 93 }
原文:http://www.cnblogs.com/--ZHIYUAN/p/6011504.html