POJ 2386 DFS deep search entry

Time Limit: 1000MS

 

Memory Limit: 65536K

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.

Problem-solving ideas

DFS simple entry, after WA has been written, and have not found a note before considerations of scanf, cin reads the character will automatically ignore line breaks and spaces, but scanf does, so when it comes to use line breaks and spaces getchar () to skip the line breaks and spaces.

AC Code

#include<cstdio>
#include<cstring>
using namespace std;

const  int N = 105 ;
 char Map [N] [N];
 int VIS [N] [N]; // access flag 
int n-, m;
 int DX [ . 8 ] = {- . 1 , 0 , . 1 , - . 1 , . 1 , - . 1 , 0 , . 1 };
 int Dy [ . 8 ] = { . 1 , . 1 , . 1 , 0 , 0 , - . 1 , - . 1 , - . 1 }; //Peripheral node from top to bottom, left to right eight points 
int ANS = 0 ; // Number lake

bool valid(int x, int y)
{
    return (x >= 0 && y >= 0 && x < n && y < m);
}

void DFS(int x, int y)
{
    VIS [X] [Y] = . 1 ; // accessed 
    for ( int I = 0 ; I < . 8 ; I ++ )
    {
        int newx = x + dx [i];
        int OF NEW = the + your [i];
        os (valid (newx, OF NEW))
        {
            os (map [newx] [OF NEW] == ' W ' && vis [newx] [OF NEW] == - 1 ) DFS (newx, OF NEW);
        }
    }
}

int main ()
{
    memset(vis, -1, sizeof(vis));
    scanf("%d%d", &n, &m);
    getchar();
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            scanf("%c", &map[i][j]);
        }
        getchar();
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (map[i][j] == 'W'&&vis[i][j] == -1)
            {
                years ++ ;
                DFS(i, j);
            }
        }
    }
    printf("%d", ans);
    return 0;
}

Simpler solution : do vis array directly visited "W" to become. "."

Guess you like

Origin www.cnblogs.com/yun-an/p/11104824.html