zoj 1709 Oil Deposits ——DFS入门题

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=709

题目大意:

  给一个矩阵,*代表空地,@代表油田,并且@如果水平,竖直,对角线相邻的话就认为是一块油田,问有多少块油田。

  思路就是DFS,从第一个字符开始搜,找到一个@就标记一下,cnt++,然后看它的八个方向上是不是有@,如果有,全部标记为*,不需要恢复现场。然后输出cnt的值就行了。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <cctype>
 6 #include <stack>
 7 #include <queue>
 8 #include <cmath>
 9 #include <algorithm>
10 #define lson l, m, rt<<1
11 #define rson m+1, r, rt<<1|1
12 using namespace std;
13 typedef long long int LL;
14 const int MAXN =  0x3f3f3f3f;
15 const int  MIN =  -0x3f3f3f3f;
16 const double eps = 1e-9;
17 
18 char s[110][110];
19 bool flag;
20 int cnt, n, m;
21 int dir[8][2] = {{0,1},{0,-1},{-1,0},{1,0},{1,1},{-1,1},{1,-1},{-1,-1}};
22 void dfs(int i, int j){
23   if (i < 0 || j < 0 || i > m || j > n) return;
24   if (s[i][j] == '*') return;
25   if (s[i][j] == '@') flag = true;
26   s[i][j] = '*';
27   for (int k = 0; k < 8; ++k){
28     if (s[i+dir[k][0]][j+dir[k][1]] == '@'){
29       dfs(i+dir[k][0], j+dir[k][1]);
30     }
31   }
32 }
33 int main(void){
34 #ifndef ONLINE_JUDGE
35   freopen("zoj1709.in", "r", stdin);
36 #endif
37   while (~scanf("%d%d", &m, &n) && (m+n)){
38     cnt = 0; flag = false;
39     for (int i = 0; i < m; ++i){
40       scanf("%s", s[i]);
41     }
42     for (int i = 0; i < m; ++i){
43       for (int j = 0; j < n; ++j){
44         flag = false;
45         dfs(i, j);
46         if (flag) cnt++;
47       }
48     }
49     printf("%d\n", cnt);
50   }
51 
52   return 0;
53 }

自己写的,好久不1A了……虽然题目很简单,但还是很高兴~O(∩_∩)O哈哈~

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