E - Lake Counting
Time Limit:1000MS MemoryLimit:65536KB 64bit IO Format:%I64d& %I64u
Submit Status Practice POJ 2386
Description
Due to recentrains, water has pooled in various places in Farmer John's field, which isrepresented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100)squares. Each square contains either water ('W') or dry land ('.'). Farmer Johnwould like to figure out how many ponds have formed in his field. A pond is aconnected set of squares with water in them, where a square is consideredadjacent to all eight of its neighbors.
Given a diagram of Farmer John's field, determine how many ponds he has.
Input
* Line 1: Twospace-separated integers: N and M
* Lines 2..N+1: M characters per line representing one row of Farmer John'sfield. Each character is either 'W' or '.'. The characters do not have spacesbetween them.
Output
* Line 1: Thenumber 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
——————————————————————————————————
读题目就知道,这个是计算W可以连成多少个小湖的问题,而且他规定可以上下左右斜上斜下这样去寻找,
这时候要想到搜索这部分,也就是BFS和DFS,BFS是寻找最短路径的,在这题目中并不适合,所以直接用DFS就可以了,一直走。
这题目只需要计算湖水的个数,跟一般的DFS题目还不一样,不需要去记录步数,所以直接将输入的示例通过上下左右斜上斜下这样把水W变成点 (这道题是不完整的DFS,但是简单)。
整理下思路:先读入到数组里面,然后先通过暴力,一个一个点去寻找,遇到了W点,计算所用变量加1,将这个点的坐标放入DFS中,将相邻的W全部变成点 。 ,搜索完后退出,继续暴力搜索,再次遇到重复刚才步骤,直到全部搜索完。
以下是代码实现:
#include<stdio.h>
const int maxn=100+5;
char tuxing[maxn][maxn];
int hang,lie;
void dfs(int x,int y)
{
intnx,ny;
inti,j;
for(i=-1;i<2;i++) //这两个for循环是用来向八个方向上下左右斜上斜下搜索的
//也可以用一个数组a[][2]={1,0,-1,0,0,1,0,-1,1,1,1,-1,-1,1,-1,-1}来向八个方向搜索
for(j=-1;j<2;j++)
{
nx=x+i; //生成新的x和y坐标
ny=y+j;
if(nx>=0&&nx<hang&&ny>=0&&ny<lie&&tuxing[nx][ny]=='W') //DFS或者BFS都需要一个限制条件,这个地方就保证
//新的x和y坐标不会越界且新的(x,y)点是W
{
tuxing[nx][ny]='.';
dfs(nx,ny);
}
}
}
int main()
{
intnum=0;
inti,j;
scanf("%d%d",&hang,&lie);
for(i=0;i<hang;i++)
scanf("%s",&tuxing[i]); //读入所给数据,这个地方我一开始是用的%c来读取,这就会出现一个问题,会读取到‘/n’,所以 //用%s是最方便快捷的
for(i=0;i<hang;i++)
for(j=0;j<lie;j++)
if(tuxing[i][j]=='W')
{
tuxing[i][j]='.'; //这一步其实加不加都无所谓,首先dfs中斜上斜下寻找会将他变成‘。’,其次,这个点在
//暴力搜索中也不会再回来找这个点的,不会让计数用的num++。但也有个问题,运算上大了点
dfs(i,j);
num++;
}
printf("%d",num);
}