lightoj 1397 - Sudoku Solver

思路:每次找出可能情况最少的位置枚举可能情况!!!

poj2676和这题一样不过poj数据比较水,很容易过。

代码如下:

 

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #define M 100005
 5 using namespace std;
 6 char str[9][9];
 7 struct point
 8 {
 9     int x,y;
10 }p[82];
11 int cnt,tot;
12 bool is_ok(int x,int y,char c) //判断c是否可以放
13 {
14     int u=x/3*3;
15     int v=y/3*3;
16     for(int i=0;i<3;i++) //3x3的小格子
17         for(int j=0;j<3;j++)
18             if(str[u+i][v+j]==c) return 0;
19     for(int i=0;i<9;i++) //行和列
20         if(str[i][y]==c||str[x][i]==c) return 0;
21     return 1;
22 }
23 void find_best_way(int &x,int &y) //找出可能情况最少的位置
24 {
25     int best=10;
26     for(int i=0;i<cnt;i++){
27         if(str[p[i].x][p[i].y]!='.') continue;
28         int num=0;
29         for(char j='1';j<='9';j++)
30             if(is_ok(p[i].x,p[i].y,j)) num++;
31         if(num<best) x=p[i].x,y=p[i].y,best=num;
32     }
33 }
34 bool dfs()
35 {
36     if(tot==0){
37         for(int i=0;i<9;i++){
38             for(int j=0;j<9;j++)
39                 printf("%c",str[i][j]);
40             printf("\n");
41         }
42         return 1;
43     }
44     int x,y;
45     find_best_way(x,y);
46     tot--;
47     for(char j='1';j<='9';j++){
48         if(is_ok(x,y,j)){
49             str[x][y]=j;
50             if(dfs()) return 1;
51         }
52     }
53     tot++;
54     str[x][y]='.';
55     return 0;
56 }
57 int main()
58 {
59     int t,ca=0,n,m,a;
60     scanf("%d",&t);
61     while(t--){
62         cnt=0;
63         for(int i=0;i<9;i++){
64             scanf("%s",str[i]);
65             for(int j=0;j<9;j++)
66                 if(str[i][j]=='.'){
67                     p[cnt].x=i;
68                     p[cnt++].y=j;
69                 }
70         }
71         tot=cnt;
72         printf("Case %d:\n",++ca);
73         dfs();
74     }
75     return 0;
76 }
View Code

 

 

 

posted @ 2013-10-03 10:37  _随心所欲_  阅读(420)  评论(0编辑  收藏  举报