题目:
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.
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.
* 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
下面是一个正确的代码。
#include<stdio.h>
#define MAXN 110
char ww[MAXN][MAXN];
int vis[MAXN][MAXN];
int f=0;
int n,m;
void search(int x,int y)
{
if(x<0||x>=n||y<0||y>=m||vis[x][y]||ww[x][y]=='.') return;
vis[x][y]=1;
search(x+1,y);
search(x+1,y+1);
search(x+1,y-1);
search(x-1,y);
search(x-1,y+1);
search(x-1,y-1);
search(x,y+1);
search(x,y-1);
}
main()
{
char z;
int i,j;
int x,y;
for(i=0;i<MAXN;i++)
{
for(j=0;j<MAXN;j++)
vis[i][j]=0;
}
scanf("%d%d",&n,&m);
scanf("%s",ww[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(!vis[i][j]&&ww[i][j]=='W'){
search(i,j);
f++;
}
}
}
printf("%d\n",f);
}
下面是一个错误的代码:
#include<stdio.h>
#define MAXN 110
char ww[MAXN][MAXN];
int vis[MAXN][MAXN];
int f=0;
void search(int x,int y)
{
vis[x][y]=1;
if(!vis[x][y]&&ww[x][y]=='W')
{
search(x+1,y);
search(x+1,y+1);
search(x+1,y-1);
search(x-1,y);
search(x-1,y+1);
search(x-1,y-1);
search(x,y+1);
search(x,y-1);
}
}
main()
{
int i,j;
int n,m;
int x,y;
for(i=0;i<MAXN;i++)
{
for(j=0;j<MAXN;j++)
vis[i][j]=0;
}
scanf("%d%d",&n,&m);
getchar();
for(i=0;i<MAXN;i++)
{
for(j=0;j<MAXN;j++)
ww[i][j]='.';
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
getchar(ww[i][j]);
getchar();
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
printf("%c\n",ww[i][j]);
if(!vis[i][j]&&ww[i][j]=='W'){
search(i,j);
f++;
}
}
}
printf("%d\n",f);
}
上面的代码中有两处错误,但是我不知道具体哦原因。
一处是gerchar的使用会使编译器报错。
另一处是深搜函数有问题,可能不执行递归。
没有进行调试,具体原因不清楚。