poj1272 棋盘问题 ——DFS入门题

题目链接:http://poj.org/problem?id=1321

题目大意:

  中文题,省了……

题目思路:

  感觉搜索题目还是要多做,很多东西都是开始看起来很复杂,其实根本就没有那么复杂,比如说这道,实际上就比较基础,可是,自己还是做不出来……o(╯□╰)o

  这道题目需要注意的一点就是:先DFS一行,然后要注意,要考虑当前行不放,直接DFS下一行!这个情况赶脚还是比较不容易想到的,虽然做完之后感觉也挺自然啊,可是……当初为毛想不到。。。就是思维的问题吧……代码看的是这位仁兄的:http://fuliang.iteye.com/blog/398700THX……^_^

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <cctype>
 6 #include <stack>
 7 #include <queue>
 8 #include <deque>
 9 #include <map>
10 #include <set>
11 #include <vector>
12 #include <cmath>
13 #include <algorithm>
14 #define lson l, m, rt<<1
15 #define rson m+1, r, rt<<1|1
16 using namespace std;
17 typedef long long int LL;
18 const int MAXN =  0x7fffffff;
19 const int  MINN =  -0x7fffffff;
20 const double eps = 1e-9;
21 const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
22   {1,1},{1,-1},{-1,-1}};
23 const int MAX = 10;
24 char m[MAX][MAX];int cnt, n, k, sum;
25 bool p[MAX];
26 bool judge(int i, int j) {
27   if (p[j] == false && m[i][j] == '#') return true;
28   else return false;
29 }
30 void dfs(int x) {
31   if (sum == k) {cnt++; return;}
32   if (x >= n) return;
33   int i;
34   for (i = 0; i < n; ++i) {
35     if (judge(x, i)) {
36       p[i] = true; sum++; dfs(x+1);
37       p[i] = false; sum--;
38     }
39   }
40   dfs(x + 1);
41 }
42 int main(void){
43 #ifndef ONLINE_JUDGE
44   freopen("poj1321.in", "r", stdin);
45 #endif
46   while (~scanf("%d%d", &n, &k)) {
47     int i, j;
48     if (k == -1 && n == -1) break;
49     //getchar();
50     for (i  = 0; i <n ; ++i) {
51       for (j = 0; j < n; ++j) {
52         //scanf("%c", &m[i][j]);
53         cin>>m[i][j];
54       }
55       //getchar();
56     }
57     cnt = 0;
58     memset(p, false, sizeof(p));
59     sum = 0;
60     dfs(0);
61     printf("%d\n", cnt);
62   }
63 
64   return 0;
65 }

还有一个地方不懂……就是注释的那三行,如果把那三行的注释符号去掉,再把cin那一行删掉,也是可以过的。

就是不明白为什么用scanf()读入一行一行的字符串也需要用getchar()?当初纠结好久……原来连读入都没有处理好……

还有就是,这题过了以后,为了测试一下加getchar()是不是也可以过,然后就是各种WA啊……就不明白了,为什么刚才还可以过的代码,现在就WA了……好吧……后来才发现因为开了许多窗口,交错题了o(╯□╰)o多么奇葩的错误……

原文地址:https://www.cnblogs.com/liuxueyang/p/3074971.html