Sudoku(dfs)

http://poj.org/problem?id=2676

填九宫格

思路:将每一行,每一列及每一个3*3块中出现的数字标记上,将可填的空的位置记录下来,枚举1-9,填入合适的数。

 1 #include <stdio.h>
 2 #include <string.h>
 3 int row[10][10],col[10][10],arr[10][10];//row[x][i]表示i所在的行为x;
 4                                         //col[y][i]表示i所在的列为y;
 5                                         //arr[n][i]表示i所在的3*3方格;
 6 int keep[82][2],map[10][10],num,t;      //keep[][]记录可填数的位置;
 7 void show()
 8 {
 9     for (int i = 0;i < 9;i ++)
10     {
11         for (int j = 0;j < 9;j ++)
12         {
13             printf("%d",map[i][j]);
14         }
15         puts("");
16     }
17 }
18 int dfs(int x,int y)
19 {
20     if (t==num)
21     {
22         show();
23         return 1;
24     }
25     for (int i = 1;i <= 9;i ++)
26     {
27         int k = x/3*3+y/3;
28         if (!row[x][i]&&!col[y][i]&&!arr[k][i])
29         {
30             map[x][y] = i;
31             row[x][i] = 1;
32             col[y][i] = 1;
33             arr[k][i] = 1;
34             ++t;
35             if (dfs(keep[t][0],keep[t][1]))
36             return 1;
37             --t; 
38             //回溯过程中,清除标记
39             map[x][y] = 0;
40             row[x][i] = 0;
41             col[y][i] = 0;
42             arr[k][i] = 0;
43 
44         }
45     }
46     return 0;
47 
48 }
49 int main()
50 {
51     int T;
52     scanf("%d",&T);
53     while(T--)
54     {
55          t = 0;
56          memset(row,0,sizeof(row));
57          memset(col,0,sizeof(col));
58          memset(arr,0,sizeof(arr));
59          memset(keep,0,sizeof(keep));
60         for (int i = 0;i < 9;i ++)
61         {
62             for (int j = 0;j < 9;j ++)
63             {
64                 scanf("%1d",&map[i][j]);//控制格式输入
65                 if (map[i][j])
66                 {
67                     int k = i/3*3+j/3;
68                     row[i][map[i][j]] = 1;
69                     col[j][map[i][j]] = 1;
70                     arr[k][map[i][j]] = 1;
71                 }
72                 else
73                 {
74                     keep[t][0] = i;
75                     keep[t++][1] = j;
76                 }
77             }
78         }
79         num = t;
80         t = 0;
81         dfs(keep[t][0],keep[t][1]);
82     }
83    return 0;
84 }
View Code

 

posted @ 2013-08-30 17:26  N_ll  阅读(173)  评论(0编辑  收藏  举报