1----Lake Counting (dfs--深度搜索)

Lake Counting (dfs–深度搜索)


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 
#include
#include"string.h"
#include"math.h"
using namespace std;
int m,n;//全局变量
char a[105][105];
void dfs(int x,int y)
{
    a[x][y]='.';
    for(int i=-1; i<=1; i++)//
        for(int j=-1; j<=1; j++)//对某一位置的周围8块位置进行判断
        {
            int  nx=x+i,ny=y+j;
            if(nx>=0&&nxW'&&ny=0)//递归条件
               {
                dfs(nx,ny);
                }
        }
    return ;
}
int main()
{
    int i,j,k;
    while(~scanf("%d %d",&m,&n))
    {
        k=0;
        for(i=0; i"%s",a[i]);
        for(i=0; ifor(j=0; jif(a[i][j]=='W')
                {
                    dfs(i,j);
                    k++;
                }
            }
        printf("%d\n",k);
    }
    return 0;
}

思路:先对输入的图形进行遍历,找到W,然后对其进行深搜将与其相连的所有W变成‘’.‘’,最后深搜的次数就是所要求的水洼的个数

你可能感兴趣的:(1----Lake Counting (dfs--深度搜索))