Poj2386 Lake counting (DFS)

Source: Internet
Author: User

Starting from any W, the adjacent part is replaced. After one DFS operation, all the WS connected to the initial W will be replaced with '.', so until w no longer exists in the figure, the total number of DFS operations is the answer. Eight statuses are transferred in eight directions. Each grid is called once as a DFS parameter, so the complexity is O (8 × n × m) = O (n × m ).

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;char map[110][110];int dis[8][2]={{0,1},{1,0},{-1,0},{0,-1},{1,1},{-1,-1},{-1,1},{1,-1}};int n,m;void dfs(int x,int y){    map[x][y]='.';    for(int i=0;i<8;i++)    {        int xx=x+dis[i][0];        int yy=y+dis[i][1];        if(xx<0||xx>=n||yy<0||yy>=m) continue;        if(map[xx][yy]=='W')        {            dfs(xx,yy);        }    }    return;}int main(){    //freopen("d:\\test.txt","r",stdin);    while(cin>>n>>m)    {        for(int i=0;i<n;i++)        {            for(int j=0;j<m;j++)            {                cin>>map[i][j];            }        }        int ans=0;        for(int i=0;i<n;i++)        {            for(int j=0;j<m;j++)            {                if(map[i][j]=='.') continue;                dfs(i,j);                ans++;            }        }        cout<<ans<<endl;    }    return 0;}


Poj2386 Lake counting (DFS)

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.