POJ 2386 Lake Counting (Dfs-floodfill)

Source: Internet
Author: User
Topic links

POJ 2386 Topic

Given a n*m map, ' W ' indicates stagnant water, '. ' Indicates the open space, the water is eight connected, ask how many water blocks. Analysis

The topic is a typical solution to the number of pieces of the basic problem, the idea is to use floodfill (diffuse water filling method), scan a picture, each encounter a ' W ' counter plus one, and deep search or wide search to the adjacent ' W ' fill as '. ' Until there is no water on the chart.
pay attention to the input of the string: either use CIN or use GetChar () to handle the line break. Code

#include <iostream> #include <cstdio> using namespace std;
Char field[1001][1001];
int n,m;
    void Dfs_floodfill (int x,int y)//floodfill {field[x][y]= '. ';
        for (int dx=-1;dx<=1;dx++) for (int dy=-1;dy<=1;dy++) {int xx=x+dx;
        int yy=y+dy; if (xx>=1&&xx<=n&&yy>=1&&yy<=m&&field[xx][yy]== ' W ') DFS_floodfill (
    XX,YY);
    }} int main () {int i,j,ans;
        while (scanf ("%d%d", &n,&m)!=eof) {GetChar ();//Note that there are line breaks before entering the map, it is important.
            for (i=1;i<=n;i++) {for (j=1;j<=m;j++) scanf ("%c", &field[i][j]);
        GetChar ();
        } ans=0;
                    for (i=1;i<=n;i++) for (j=1;j<=m;j++) if (field[i][j]== ' W ') {
                    Dfs_floodfill (I,J);
                ans++;
    } cout<<ans<<endl;
} return 0;
 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.