poj2676 Sudoku(DFS)

做了很久还是参考了别人的答案orz,其实也不难啊。我要开始学一下怎么写搜索了。。。

题目链接:poj2676 Sudoku

题解:暴力搜索,DFS每个空白格子所放数字。

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<vector>
 6 using namespace std;
 7 bool row_f[9][10];//row_f[i][j]=1表示第i行已经放了数字j
 8 bool col_f[9][10];
 9 bool block_f[9][10];
10 int g[9][9];
11 struct blank{
12     int i, j;
13     blank(int i, int j):i(i),j(j) {}
14 };
15 vector<blank> bk;
16 int get_blockid(int i, int j){
17     i /= 3;
18     j /= 3;
19     return i * 3 + j;
20 }
21 bool ok(int i, int j, int x){
22     return !row_f[i][x] && !col_f[j][x] && !block_f[get_blockid(i, j)][x];
23 }
24 void setnum(int i, int j, int x, int f){
25     row_f[i][x] = f;
26     col_f[j][x] = f;
27     block_f[get_blockid(i, j)][x] = f;
28 }
29 bool dfs(int n){//处理前n个空白格
30     if(n < 0) return true;
31     int r = bk[n].i;
32     int c = bk[n].j;
33     for(int x = 1; x <= 9; ++x){
34         if(ok(r, c, x)){
35             setnum(r, c, x, 1);
36             g[r][c] = x;
37             if(dfs(n - 1)) return true;
38             setnum(r , c, x, 0);
39         }
40     }
41     return false;
42 }
43 int main(){
44     int t, i, j;
45     char c;
46     scanf("%d", &t);
47     while(t--){
48         bk.clear();
49         memset(row_f, 0, sizeof(row_f));
50         memset(col_f, 0, sizeof(col_f));
51         memset(block_f, 0, sizeof(block_f));
52         for(i = 0; i < 9; ++i){
53             for(j = 0 ;j < 9; ++j){
54                 cin >> c;
55                 g[i][j] = c - '0';
56                 if(!g[i][j])
57                     bk.push_back(blank(i, j));
58                 else
59                     setnum(i, j, g[i][j], 1);
60             }
61         }
62         if(dfs(bk.size()-1)){
63             for(i = 0; i < 9; ++i){
64                 for(j = 0; j < 9 ; ++j)
65                     printf("%c", g[i][j] + '0');
66                 printf("\n");
67             }
68         }
69     }
70     return 0;
71 }
View Code

 

posted @ 2016-09-11 16:42  GraceSkyer  阅读(278)  评论(0编辑  收藏  举报

~~~~~~ACM大牛语录,激励一下~~~~~~

为了世界的和平,为了女生的安全,我拼命做题,做题,做题!

用最短的时间,刷最多的题!

给我一滴泪,我就看到了你全部的海洋!

seize the hour, seize the day.

人生难免有无奈,幸福走远了,或是感叹幸福来迟了.其实我一直相信,无论手中的幸福是多么微不足道的感觉,我会把握住那每一分,每一秒,当幸福依旧像那百鸟般飞逝,终究无法掌握时,我会感谢它,曾经降临过!

A自己的题,让别人郁闷去吧

WA肠中过,AC心中留 TLE耳边过,AC特别牛

天然的悲苦和伤逝,过去有过,以后还会有

^*^一步一步往上爬^*^

AC就像练级,比赛就像PK. 练级不如PK好玩

其实,世上本没有ACM,AC的人多了,也便有了!

AC无止尽~ Seek you forever~

找呀找呀找水题,找到一个AC一个呀!

AC是检验程序的唯一标准。

真的猛士,敢于直面惨淡的人生,敢于正视淋漓的鲜血……