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
#include<cstdio>
#include <iostream>
#include<cstring>
using namespace std;
char map[101][101];///一直开了50那么大,都是不好好读题的结果!!!
/*const int dx[4] = {0,0,-1,1};
const int dy[4] = {-1,1,0,0};*/
int r, c;
void dfs(int x,int y)
{
map[x][y] = '.';
/*if(x>=r || x<0)
return;
if(y>=c || y<0)
return;*没什么用,因为前面已经限制过了
int x_new,y_new;
/*for(int i=0; i<4; i++)
{
x_new = x + dx[i];
y_new = y + dy[i];
if(x_new>=0 && x_new<r && y_new>=0 && y_new<c && map[x_new][y_new] == 'W')
{
dfs(x_new,y_new);
}
}*这样写的话,缺少(-1,-1),(1,1),(-1,1),(1,-1)这四种情况
for(int dx=-1; dx<=1; dx++)
{
for(int dy = -1; dy<=1; dy++)
{
x_new = x + dx;
y_new = y + dy;
if(x_new>=0 && x_new<r && y_new>=0 && y_new<c && map[x_new][y_new] == 'W')
{
dfs(x_new,y_new);
}
}
}
return;
}
int main()
{
int cnt = 0;
scanf("%d%d",&r, &c);
/*for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
scanf("%c", &map[i][j]);
if(map[i][j] == 'W')
{
dfs(i,j);
cnt++;
}
}
}*刚开始时一直这么写,导致结果不对。
for(int i=0; i<r; i++)
scanf("%s", map[i]);
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
if(map[i][j] == 'W')
{
dfs(i,j);
cnt++;
}
}
}
printf("%d\n",cnt);
return 0;
}
这道题做得太不容易了,老是想错。
竟然有点怀疑poj了,真傻,出错的只会是自己啊!!!