DFS 之 poj 2386 Lake Counting

//  [11/1/2014 JmingS]
/*
遍历整个图,找到 'W' 的点,对其周围八个点其进行深搜,若是 'W' 则用 '.' 替换。
最后,在遍历整个图的过程中,找到多少个 'W',即答案。。。
*/
 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <cstdio>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <functional>
 7 #include <string>
 8 #include <cstring>
 9 #include <vector>
10 #include <stack>
11 #include <queue>
12 #include <map>
13 using namespace std;
14 #define eps 1e-8
15 #define MAX 105
16 
17 int N, M;
18 char Graph[MAX][MAX];
19 const int direction[8][2] = { { -1, 1 }, { 0, 1 }, { 1, 1 }, { -1, 0 }, { 1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 } };
20 
21 void Dfs(int x, int y) {
22     Graph[x][y] = '.';
23     for (int i = 0; i < 8; ++i) {
24         int tx = x + direction[i][0], ty = y + direction[i][1];
25         if ((tx >= 0) && (tx < N) && (ty >= 0) && (ty < M) && ('W' == Graph[tx][ty])) {
26             Dfs(tx, ty);
27         }
28     }
29     return;
30 }
31 
32 void Solve() {
33     int Sum = 0;
34     for (int i = 0; i < N; ++i) {
35         for (int j = 0; j < M; ++j) {
36             if ('W' == Graph[i][j]) {
37                 Dfs(i, j);
38                 //cout << i << "  " << j << endl;
39                 ++Sum;
40             }
41         }
42     }
43     printf("%d\n", Sum);
44 }
45 
46 int main()
47 {
48     //freopen("input.txt", "r", stdin);
49     scanf("%d %d", &N, &M);
50     for (int i = 0; i < N; ++i) {
51         getchar();
52         for (int j = 0; j < M; ++j) {
53             scanf("%c", &Graph[i][j]);
54         }
55     }
56     Solve();
57     return 0;
58 }
posted @ 2014-11-01 12:59  JmingS  阅读(201)  评论(0编辑  收藏  举报