HDU 1426 - Sudoku Killer
填数独
DFS里枚举0-9
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 const int d[]={1,2,3,4,5,6,7,8,9}; 5 char c; 6 int map[10][10]; 7 bool f; 8 inline void ch(const int& i,const int& j,const char& c ) 9 { 10 if(c=='?') map[i][j]=0 ; 11 else map[i][j] = c-'0' ; 12 } 13 bool check(const int& x,const int& y,const int& z) 14 { 15 for(int i=0;i<9;i++) 16 { 17 if(map[x][i]==d[z]) return 0; 18 if(map[i][y]==d[z]) return 0; 19 } 20 int p1=x-x%3; 21 int p2=y-y%3; 22 for(int i=p1;i<p1+3;i++) 23 { 24 for(int j=p2;j<p2+3;j++) 25 { 26 if(map[i][j]==d[z]) return 0; 27 } 28 } 29 return 1; 30 } 31 void bfs() 32 { 33 int i,j; 34 bool p=0; 35 for(i=0;i<9;i++) 36 { 37 for(j=0;j<9;j++) 38 { 39 if(map[i][j]==0) 40 { 41 p=1; 42 break; 43 } 44 } 45 if(p) break; 46 } 47 if(i==9) 48 { 49 f=1; 50 return; 51 } 52 for(int k=0;k<9;k++) 53 { 54 if(check(i,j,k)) 55 { 56 map[i][j]=d[k]; 57 bfs(); 58 } 59 if(f) return; 60 } 61 62 map[i][j]=0; 63 } 64 int main() 65 { 66 int t=0; 67 while(~scanf(" %c",&c)) 68 { 69 if(t) puts(""); 70 f=0; 71 ch(0,0,c); 72 for(int j=1;j<9;j++) 73 { 74 scanf(" %c",&c); 75 ch(0,j,c); 76 } 77 for(int i=1;i<9;i++) 78 { 79 for(int j=0;j<9;j++) 80 { 81 scanf(" %c",&c); 82 ch(i,j,c); 83 } 84 } 85 bfs(); 86 for(int i=0;i<9;i++) 87 { 88 for(int j=0;j<9;j++) 89 { 90 if(j) printf(" "); 91 printf("%d",map[i][j]); 92 } 93 printf("\n"); 94 } 95 t=1; 96 } 97 }
我自倾杯,君且随意