poj2386(简单的dfs/bfs)

时间:2022-06-12 16:24:32

题目链接:http://poj.org/problem?id=2386

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.

题意:有一个大小为N*M的园子,雨后起了水。八连通的积水都被认为是连接在一起的。请求出园子里总共有多少水洼?(八连通指的是下图中相对W的*部分)
***
*W*
***
解题思路:从任意的W开始,不停把邻接的部分用'.'代替。1次dfs后与初始的这个W连接的所有W就都被替换成了'.',因此知道图中不在出现'W'为止,总共进行dfs的次数就是最后的答案了,8个方向对应8种状态转移,每个格子作为dfs的参数之多被调用一次,所以复杂度为O(8*n*m)=O(n*m)。
附上代码:
 #include<iostream>
#include<cstdio>
using namespace std;
char map[][];
int n,m;
int dir[][]={{-,-},{-,},{-,},{,-},{,},{,-},{,},{,}};
//现在位置为(x,y)
void dfs(int x,int y)
{
//将现在所在位置替换为.
map[x][y]='.';
//循环遍历移动的8个方向
for(int i=;i<;i++)
{
int dx=x+dir[i][];
int dy=y+dir[i][];
//判断(dx,dy)内是否又水
if(dx>=&&dx<n&&dy>=&&dy<m&&map[dx][dy]=='W') dfs(dx,dy);
} }
int main()
{
cin>>n>>m;
int res=;
getchar(); //吸收回车符
for(int i=;i<n;i++){
for(int j=;j<m;j++){
scanf("%c",&map[i][j]);
}
getchar();// 将回车符读掉
}
for(int i=;i<n;i++)
{
for(int j=;j<m;j++)
{
//从有水的地方开始dfs
if(map[i][j]=='W')
{
dfs(i,j);
res++;
}
}
}
cout<<res<<endl;
return ;
}