Lake Counting (POJ No.2386)

 深度优先搜索的用法——lake counting

问题主题:Lake Counting

问题描述:

有一个大小为N*M的园子,雨后积了很多水。八连通的积水被认为是在一起的。请求出园子里共有多少个水洼?(八连通是指下图中相对+的*部分)

+++

+*+

+++

限制条件:

N,M <= 100


样例:

输入

N=10, M=12

园子如下图(‘+’表示积水,’*’表示没有积水)

+********++*

*+++*****+++

****++***++*

*********++*

*********+**

**+******+**

*+*+*****++*

+*+*+*****+*

*+*+******+*

**+*******+*

 1 int N, M;
 2 char field[MAX_N][MAX_N + 1];//园子
 3 //现在位置(x, y)
 4 void dfs(int x, int y)
 5 {
 6     //将现在的位置替换为“.”
 7     field[x][y] = '.';
 8     //循环遍历移动的8个方向
 9     for(int dx = -1; dx <= 1; dx++)
10     {
11         for(int dy = -1; dy <= 1; dy++)
12         {
13             //向x方向移动dx,向y方向移动dy,移动的效果为(nx, ny)
14             int nx = x + dx, ny = y + dy;
15             if(0 <= nx && nx < N && 0 <= ny && ny < M && field[nx][ny] == 'w')
16                 dfs(nx, ny);
17         }
18     }
19     return;
20 }
21 
22 void solve()
23 {
24     int res = 0;
25     for(int i = 0; i < N; i++)
26     {
27         for(int j = 0; j < M; j++)
28         {
29             if(field[i][j] == 'W')
30             {
31                 dfs(i, j);
32                 res++;
33             }
34         }
35     }
36     cout << res << endl;
37 }


原文地址:https://www.cnblogs.com/CZT-TS/p/7643496.html