Lake Counting(DFS连通图)

本文介绍了一种基于深度优先搜索算法解决求解二维网格中水塘数量问题的方法。通过遍历矩阵并标记已访问过的水域,实现统计独立水塘的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water ('W') or dry land ('.'). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors. 

Given a diagram of Farmer John's field, determine how many ponds he has.

Input

* Line 1: Two space-separated integers: N and M 

* Lines 2..N+1: M characters per line representing one row of Farmer John's field. Each character is either 'W' or '.'. The characters do not have spaces between them.

Output

* Line 1: The number of ponds in Farmer John's field.

Sample Input

10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.

Sample Output

3

Hint

OUTPUT DETAILS: 

There are three ponds: one in the upper left, one in the lower left,and one along the right side.

 

 题目意思:查找所有由w组成的区域,八面搜索,只要周围有w就能连接在一起组成一个区域。
 解题思路:这是一道很基本的深搜例题,当成模板直接来使用吧。
 
上代码:
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 #include<iostream>
 5 using namespace std;
 6 char map[110][110];
 7 int vis[110][110];///标记数组
 8 int dir[8][2]={{1,0},{-1,0},{0,1},{0,-1},{1,1},{-1,-1},{1,-1},{-1,1}};
 9 int n,m;
10 void DFS(int x,int y)
11 {
12     int a,b,i;
13     vis[x][y]=1;
14     for(i=0;i<8;i++)
15     {
16         a=x+dir[i][0];
17         b=y+dir[i][1];
18         if(a>=0&&a<n&&b>=0&&b<m&&vis[a][b]==0&&map[a][b]=='W')
19         {
20             DFS(a,b);
21         }
22     }
23         return ;
24 }
25 int main()
26 {
27     int count,i,j;
28     memset(map,0,sizeof(map));
29     memset(vis,0,sizeof(vis));
30     scanf("%d%d",&n,&m);
31     getchar();
32     count=0;
33     for(i=0;i<n;i++)
34     {
35         scanf("%s",map[i]);
36     }
37     for(i=0;i<n;i++)
38     {
39         for(j=0;j<m;j++)
40         {
41             if(vis[i][j]==0&&map[i][j]=='W')
42             {
43                 count++;
44                 DFS(i,j);
45             }
46         }
47     }
48     printf("%d\n",count);
49     return 0;
50 }

 

转载于:https://www.cnblogs.com/wkfvawl/p/8904454.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值