题目:
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
- Line 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
分析:bfs搜索,遍历整个数组,遇到W就入队,并把与其相连的W全部入队,入队后将该元素标记为’.’,每bfs一次答案就加一。需要注意的是这题把一个点周围八个点全部视为相连的。
由于数据规模较小(100*100),也可以dfs,每次找到一个W就dfs这个W周围是否还有并标记。
代码:
BFS:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,m,a[110][110],ans;
void bfs(int x1,int y1)
{
int queue[10100][2],l=0,r=1,x,y;
int p[]={0,0,1,-1,-1,1,1,-1},q[]={1,-1,0,0,-1,-1,1,1};
memset(queue,0,sizeof(queue));
queue[1][1]=x1;
queue[1][2]=y1;
a[x1][y1]=0;
while (l<r)
{
l++;
for (int i=0;i<8;i++)
{
x=queue[l][1]+p[i];
y=queue[l][2]+q[i];
if (x<=n && y<=m && a[x][y]==1 && x>=1 && y>=1)
{
r++;
queue[r][1]=x;
queue[r][2]=y;
a[x][y]=0;
}
}
}
ans++;
}
int main()
{
char s[110];
cin>>n>>m;
for (int i=1;i<=n;i++)
{
scanf("%s",s);
for (int j=0;j<strlen(s);j++)
if (s[j]=='W') a[i][j+1]=1;
}
for (int i=1;i<=n;i++)
{
for (int j=1;j<=m;j++)
{
if (a[i][j])
bfs(i,j);
}
}
cout<<ans;
return 0;
}
DFS:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int a[110][110],n,m,ans=0;
int dx[]={0,0,-1,1,-1,1,-1,1},dy[]={1,-1,0,0,1,1,-1,-1};
void dfs(int x1,int y1)
{
int x,y;
for (int i=0;i<8;i++)
{
x=x1+dx[i];
y=y1+dy[i];
if (x>0 && y>0 && x<=n && y<=m && a[x][y]==1)
{
a[x][y]=0;
dfs(x,y);
}
}
}
int main()
{
memset(a,0,sizeof(a));
char s[110];
cin>>n>>m;
for (int i=1;i<=n;i++)
{
cin>>s;
for (int j=0;j<m;j++)
{
if (s[j]=='W')
a[i][j+1]=1;
}
}
for (int i=1;i<=n;i++)
{
for (int j=1;j<=m;j++)
{
if (a[i][j])
{
ans++;
a[i][j]=0;
dfs(i,j);
}
}
}
cout<<ans;
}