HDU 2952 Counting Sheep (DFS找聯通塊)

來源:互聯網
上載者:User

標籤:hdu2952   counting sheep   dfs   hdu   

題目連結:請戳這裡。   題目大意及思路:讀懂題意就好了,就是DFS找聯通塊。

沒什麼好說的,見代碼吧。

#include<cstdio>#include<cstring>#include<algorithm>#define N 100+5using namespace std;int n,m;char g[N][N];int dir[4][2]={1,0,0,1,-1,0,0,-1};void dfs(int x,int y){    for(int i=0;i<4;i++)    {        int nx=x+dir[i][0],ny=y+dir[i][1];        if(nx>=0 && nx<n && ny>=0 && ny<m && g[nx][ny]=='#')        {            g[nx][ny]='.';  //這裡就將‘#’改成‘.’,表示已經訪問。            dfs(nx,ny);        }    }}int main(){    int T;    scanf("%d",&T);    while(T--)    {        scanf("%d%d",&n,&m);        for(int i=0;i<n;i++)            scanf("%s",&g[i]);        int ans=0;        for(int i=0;i<n;i++)        {            for(int j=0;j<m;j++)            {                if(g[i][j]=='#')                {                    g[i][j]='.';                    dfs(i,j);     //每一遍dfs後,ans就++。                    ans++;                }            }        }        printf("%d\n",ans);    }    return 0;}


HDU 2952 Counting Sheep (DFS找聯通塊)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.