【HDOJ】1426 Sudoku Killer

水水的DFS。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <vector>
 6 using namespace std;
 7 
 8 #define MAXN 18
 9 #define TOKEN '?'
10 int N = 17;
11 char map[MAXN][MAXN];
12 
13 
14 bool dfs(int x, int y) {
15     int i, j, nx, ny;
16     bool unfinish = false;
17 
18     for (i=x; i<9; ++i) {
19         for (j=(i==x)?y:0; j<N; j+=2) {
20             if (map[i][j] == TOKEN) {
21                 unfinish = true;
22                 break;
23             }
24         }
25         if (unfinish)
26             break;
27     }
28 
29     if (unfinish) {
30         nx = i;
31         ny = j;
32         int xx = i;
33         int yy = j+2;
34         bool visit[9];
35 
36         if (yy >= N) {
37             yy = 0;
38             ++xx;
39         }
40         memset(visit, false, sizeof(visit));
41         // scan the row
42         for (j=0; j<N; j+=2) {
43             if (map[nx][j] != TOKEN) {
44                 visit[map[nx][j]-'1'] = true;
45             }
46         }
47         // scan the colunm
48         for (i=0; i<9; ++i) {
49             if (map[i][ny] != TOKEN) {
50                 visit[map[i][ny]-'1'] = true;
51             }
52         }
53         // scan the closet nine
54         int p = nx/3*3;
55         int q = (ny+1)/6*6;
56         for (i=p; i<p+3; ++i) {
57             for (j=q; j<q+6; j+=2) {
58                 if (map[i][j] != TOKEN) {
59                     visit[map[i][j]-'1'] = true;
60                 }
61             }
62         }
63         for (i=0; i<9; ++i) {
64             if (visit[i] == false) {
65                 map[nx][ny] = '1'+i;
66                 if (dfs(xx, yy))
67                     return true;
68                 map[nx][ny] = TOKEN;
69             }
70         }
71         return false;
72     } else {
73         return true;
74     }
75 }
76 
77 int main() {
78     int i;
79 #ifndef ONLINE_JUDGE
80     freopen("data.in", "r", stdin);
81 #endif
82     while (1) {
83         for (i=0; i<9; ++i) {
84             gets(map[i]);
85         }
86 
87         dfs(0, 0);
88         for (i=0; i<9; ++i)
89             printf("%s\n", map[i]);
90 #ifndef ONLINE_JUDGE
91         fflush(stdout);
92 #endif
93         if (getchar() == EOF)
94             break;
95         printf("\n");
96     }
97     return 0;
98 }

 

posted on 2014-10-21 14:54  Bombe  阅读(161)  评论(0)    收藏  举报

导航