POJ 2386 Lake Counting

此题就是一个深度优先搜索的实例,遍历一遍池塘,将凡是有水的周围的八个格子进行DFS使所有'W'变成'.',这样进行了几次DFS,就有几片池塘。具体如代码。

 

题目链接:POJ 2386 Lake Counting

 

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 #define MAX_N 100
 6 #define MAX_M 100
 7 
 8 char field[MAX_N][MAX_M+1];
 9 void DFS (int n, int m);
10 int n, m;
11 
12 int main (void)
13 {
14     int count = 0;
15     while(cin>>n>>m)
16     {
17         for(int i = 0; i < n; i++)
18             for(int j = 0; j < m; j++)
19             {
20                 cin>>field[i][j];
21             }
22         for(int i = 0; i < n; i++)
23         {
24             for(int j = 0; j < m; j++)
25             {
26                 if(field[i][j] == 'W')
27                 {
28                     DFS(i,j);
29                     count++;
30                 }
31             }
32         }
33         cout<<count<<endl;
34 
35     }
36     return 0;
37 }
38 
39 void DFS (int x, int y)
40 {
41     field[x][y] = '.';
42     for(int dx = -1; dx <= 1; dx++)
43     {
44         for(int dy = -1; dy <= 1; dy++)
45         {
46             int nx = x + dx;
47             int ny = y + dy;
48             if(nx<=n && nx>= 0 && ny<= m && ny>= 0 && field[nx][ny]=='W')
49                 DFS(nx,ny);
50         }
51     }
52     return;
53 }

 



posted @ 2018-08-13 13:32  Lokianyu  阅读(144)  评论(0编辑  收藏  举报