Lake Counting
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 23950 | Accepted: 12099 |
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 这个题可以用深搜也可以用广搜,我就是从这个题,明白了两种搜索方式的不同 大家来体会一下吧! DFS版:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std; char map[][];
int mov[][]={,,,-,-,,,,,,-,-,,-,-,};
int m,n;
bool can(int x ,int y)//判断这个点能不能走
{
if(x<||x>m-||y<||y>n-||map[x][y]=='.')
return false;
return true;
} void dfs(int x,int y)
{
int i,xx,yy;
for(i=;i<;i++)
{
xx=x+mov[i][];
yy=y+mov[i][];
if(can(xx,yy))
{
map[xx][yy]='.';//走一个点就标记一下
dfs(xx,yy);
}
}
}
int main()
{
int i,j;
while(scanf("%d%d",&m,&n)!=EOF)
{
int sum=;
for(i=;i<m;i++)
scanf("%s",map[i]);
for(i=;i<m;i++)
{
for(j=;j<n;j++)
{
if(map[i][j]=='W')
{
map[i][j]='.';
dfs(i,j);//每次进入搜索函数就把这个点周围能走的点走完
sum++;
}
}
}
printf("%d\n",sum);
}
return ;
}
BFS版:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
char map[][];
int m,n;
int mov[][]={,,,-,,,-,,,,-,-,,-,-,};
struct node
{
int a,b;
}ta,tb;//定义一个结构体用来存坐标
bool can(node x)
{
if(x.a<||x.a>m-||x.b<||x.b>n-||map[x.a][x.b]=='.')
return false;
return true;
} void bfs(int x,int y)
{
queue<node> q;
ta.a=x;
ta.b=y;
q.push(ta);//入队
while(!q.empty())//直到把队列能访问的都访问过
{
int i;
ta=q.front();
q.pop();
for(i=;i<;i++)
{
tb.a=ta.a+mov[i][];
tb.b=ta.b+mov[i][];
if(can(tb))
{
map[tb.a][tb.b]='.';
q.push(tb);//如果可以访问就入队
}
}
}
} int main()
{
int i,j;
while(scanf("%d%d",&m,&n)!=EOF)
{
int sum=;
for(i=;i<m;i++)
scanf("%s",map[i]);
for(i=;i<m;i++)
for(j=;j<n;j++)
{
if(map[i][j]=='W')
{
map[i][j]='.';
bfs(i,j);
sum++;
}
}
printf("%d\n",sum);
}
return ;
}