POJ-2386--Lake Counting---DFS(深搜)

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
Hint
OUTPUT DETAILS:

There are three ponds: one in the upper left, one in the lower left,and one along the right side.

题意:有一个大小为N*M的园子,雨后积起了水,八连通的积水被认为是连接在一起的。让求出园子里有多少水洼。
八连通指的是下图中相对于W的&号的部分

&&&
&W&
&&&

解题思路:从第一个W出发,搜寻八个方向联通的W,每当找到联通的W时就把它换为’ . ‘,每次搜寻结束计数器加个1.

#include
#include 
#include
using namespace std;
int n,m;
char s[110][110];
int num=0;
void dfs(int x,int y)
{
    if(x>=0&&x=0&&y'W')//判断条件,不能出界
    {
        s[x][y]='.';
        dfs(x,y-1);
        dfs(x,y+1);
        dfs(x-1,y);
        dfs(x+1,y);
        dfs(x-1,y-1);
        dfs(x-1,y+1);
        dfs(x+1,y-1);
        dfs(x+1,y+1);
    }//个人爱好,不喜欢写for循环,八个dfs代表八个方向。简单粗暴哈哈哈
}
int main()
{
    cin>>m>>n;
    num=0;
    memset(s,'0',sizeof(s));
    int i,j;
    int t1=0,t2=0;
    for(i=0; i<=m-1; i++)
        for(j=0; j<=n-1; j++)
            cin>>s[i][j];
    for(i=0; i<=m-1; i++)
    {
        for(j=0; j<=n-1; j++)
        {
            if(s[i][j]=='W')
            {
                dfs(i,j);
                num++;
            }
        }
    }
    cout<

你可能感兴趣的:(DFS-BFS深广搜)