poj 2386Lake Counting(DFS, BFS)

             今天看了下搜索,于是找了一道DFS题来做,看过别人代码后,自己写了一下,一次AC,也可用BFS……看了一下Discuss,发现还可以用并查集来做……

Lake Counting
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 12143   Accepted: 6228

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.

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

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<stdio.h>
int N, M;
char map[101][101];
int visited[101][101]={0};
void DFS(int i, int j)
{
    if( (i<=0||i>=N+1) || (j<=0|| j>=M+1) || map[i][j]=='.' || visited[i][j] )//越界,或不存在水,或已访问过
        return;
    visited[i][j]=1;//标记
	
    DFS(i-1, j);
    DFS(i+1, j);
    DFS(i, j-1);
    DFS(i, j+1);
    DFS(i-1, j-1);
    DFS(i+1, j-1);
    DFS(i-1, j+1);
    DFS(i+1, j+1);
}
int main()
{
    int i, j, k, l;
    int num=0;
    scanf("%d %d", &N, &M);
    for(i=1; i<=N; i++)
    {
		getchar();//接受换行符
		for(j=1; j<=M; j++)
		{
			scanf("%c",&map[i][j]);
			//	cin>>map[i][j];
		}
	}
	
    for(i=1; i<=N; i++)
		for(j=1; j<=M; j++)
		{
			if(!visited[i][j] && map[i][j]=='W')//有水,且未访问过
			{
				num++;
				DFS(i, j);
			}
		}
		printf("%d\n", num);
}

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

你可能感兴趣的:(poj 2386Lake Counting(DFS, BFS))