Lake Counting -- DFS(深搜)

Time Limit: 1000MS
Memory Limit: 65536K
Total Submissions: 22424
Accepted: 11300

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.

Source

USACO 2004 November



解题分析:
首先这道题目设计几个问题:
           第一个就是怎么可以确定几个w是属于一块的。
           第二个怎么搜索。
           第三个怎么确保不会搜索重复的。
          那么第一个和第二个是一个问题,就是深度优先搜索,然后,利用递归的方法,每次对于一个点是否有8个方向,如果有的话,继续8个方向的搜索,直到到达边界为止。

      还有怎么确定不重复,那么就是我把每次找到的w都变味'  . ' 就可以了。

具体看代码。

代码:

#include <iostream>
#include <cstdio>
#define MAXN 102
using namespace std;

char map[MAXN][MAXN];
int n, m;
int DG(int i, int j) {
    if(i < 0 || i >= n || j < 0 || j >= m)
        return 0;
    if(map[i][j] == '.')
        return 0;

    map[i][j] = '.';

   
    return 1 + DG(i-1, j-1) + DG(i-1, j) + DG(i-1, j+1)
            + DG(i, j-1) + DG(i, j+1) + DG(i+1, j-1) +
            DG(i+1, j) + DG(i+1, j+1);
}

int main()
{
    cin >> n >> m;
   
    char flag;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            cin >> flag;
            map[i][j] = flag;
        }
    }

   
    int count = 0;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
         
            if(DG(i, j) != 0)
                count++;
        }
    }

    cout << count << endl;

    return 0;
}




Lake Counting -- DFS(深搜)_第1张图片

你可能感兴趣的:(Lake Counting -- DFS(深搜))