poj 2386 Lake Counting

本文介绍了一种通过深度优先搜索(DFS)算法来解决湖泊计数问题的方法。该问题源自美国计算机奥林匹克竞赛(USACO),任务是在一个由水('W')和干燥土地('.')组成的矩形网格中计算湖泊的数量。湖泊定义为相连水域的集合,每个水域与其八个相邻单元格相连。文章提供了完整的C++代码实现。
Lake Counting
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 24578 Accepted: 12407

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.

Source

 

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<stack>
 5 #include<set>
 6 #include<map>
 7 #include<queue>
 8 #include<algorithm>
 9 using namespace std;
10 char Map[105][105];
11 int n,m;
12 void dfs(int x,int y){
13     Map[x][y]='.';
14     int i,j;
15     for(i=-1;i<2;i++){
16         int xx=x+i;
17         for(j=-1;j<2;j++){
18             int yy=y+j;
19             if(xx>=0&&yy>=0&&xx<n&&yy<m&&Map[xx][yy]=='W'){
20                 dfs(xx,yy);
21             }
22         }
23     }
24 }
25 int main(){
26     //freopen("D:\\INPUT.txt","r",stdin);
27     scanf("%d %d",&n,&m);
28     int i,j,k;
29     for(i=0;i<n;i++){
30         scanf("%s",Map[i]);
31     }
32     int res=0;
33     for(i=0;i<n;i++){
34         for(j=0;j<m;j++){
35             if(Map[i][j]=='W'){
36                 dfs(i,j);
37                 res++;
38             }
39         }
40     }
41     printf("%d\n",res);
42     return 0;
43 }

 

转载于:https://www.cnblogs.com/Deribs4/p/4855058.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值