Lake Counting
题目描述:
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:
Sample Output:
题目大意:
有一块田,里面有水田和旱田,水田为W,田为“ 。”,下了一场雨,结果将一些田都变成水池,水池的规格为九宫格范围内。要求计算有多少个水池。(这里水池指的是W连在一起的为一个池塘)自己理解,如果有错误可以指出来。
思路分析:
这道题我吐了,一开始以为池塘是以一个九宫格,中间为空或者不空,周围都是水,结果发现都不符合,之后高人指点,原来是类似翻围棋,一旦有一个水池W,他的周围的W都算进去(记住是要连在一起),然后计算DFS的次数就行了。
代码:
#include<stdio.h>
#include<iostream>
int b,c;
char c1[1001][1001];
void LemonScanf()//输入田地
{
int d,e;
scanf("%d %d",&b,&c);
getchar();
for(d=0;d<b;d++)
{
gets(c1[d]);
}
}
void LemonDFS(int x,int y)
{
int d,e,x1,y1;
for(d=-1;d<=1;d++)
{
for(e=-1;e<=1;e++)//九宫格中八个方位中的情况
{
x1=x+d;
y1=y+e;
if(x1>=0 && x1<b && y>=0 && y<c && c1[x1][y1]=='W')//如果是W,说明是水池连
{ //在一起,所以都算一个
c1[x1][y1]='.';//把水田翻成旱田。
LemonDFS(x1,y1);//继续递归寻找周围的水池
}
}
}
}
int main()
{
int d,e,Waternum=0;
LemonScanf();
for(d=0;d<b;d++)
{
for(e=0;e<c;e++)
{
if(c1[d][e]=='W')
{
Waternum++;//记录水池。
LemonDFS(d,e);
}
}
}
printf("%d",Waternum);
}