poj 2386:Lake Counting(简单DFS深搜)

时间:2023-03-09 08:37:42
poj 2386:Lake Counting(简单DFS深搜)
Lake Counting
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18201   Accepted: 9192

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


  简单深搜
  遍历迷宫中所有的点,如果是‘W’,开始dfs搜索,将它临近的八个方向是‘W’的点全部走遍,并将走过的点变为‘.’,这样这一块‘W’区域就全部走完。一共走过了多少个这样的区域,就是结果。
  代码:
 #include <iostream>

 using namespace std;
int n,m;
char a[][];
int dx[] = {,,,,,-,-,-}; //八个方向
int dy[] = {,,,-,-,-,,};
bool judge(int x,int y)
{
if(x< || x>n || y< || y>m)
return ;
if(a[x][y]!='W')
return ;
return ;
}
void dfs(int x,int y)
{
a[x][y] = '.'; //将‘W’转化为‘.’
for(int i=;i<;i++){
int nx = x + dx[i];
int ny = y + dy[i];
//如果这一步是‘W’,且没有越界,可以走。
if(judge(nx,ny))
continue;
dfs(nx,ny);
}
}
int main()
{
while(cin>>n>>m){
int sum = ;
for(int i=;i<=n;i++)
for(int j=;j<=m;j++)
cin>>a[i][j];
for(int i=;i<=n;i++)
for(int j=;j<=m;j++)
if(a[i][j]=='W'){
sum++;
dfs(i,j);
}
cout<<sum<<endl;
}
return ;
}

Freecode : www.cnblogs.com/yym2013