天天看點

POJ 1979 Red and Black

題意:給一個h行w列的圖,'@'表示起始點,'.'表示可達點,'#'表示障礙,求與'@'連通的可達的點數

解題思路:深搜dfs,與水窪的那道題類似,從起始點開始沿4個方向進行dfs,如果滿足條件,就接着這個點往下搜,搜的同時記錄點的個數ans,并且标記出來,防止重複搜尋同一個點

代碼:

#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdio>
using namespace std;

int w,h,ans;
char g[25][25];
int dr[]={0,0,1,-1};
int dc[]={1,-1,0,0};
bool inside(int x,int y)
{
    return x>=0&&x<h&&y>=0&&y<w;
}
void dfs(int x,int y)
{
    ans++;
    g[x][y]='#';
    for(int i=0;i<4;i++)
    {
        int nx=x+dr[i],ny=y+dc[i];
        if(inside(nx,ny)&&g[nx][ny]=='.')
            dfs(nx,ny);
    }
    return ;
}
int main()
{
    while(cin>>w>>h&&w+h)
    {
        for(int i=0;i<h;i++)
        {
            for(int j=0;j<w;j++)
            {
                cin>>g[i][j];
            }
        }
        ans=0;
        for(int i=0;i<h;i++)
        {
            for(int j=0;j<w;j++)
            {
                if(g[i][j]=='@')dfs(i,j);
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
           

繼續閱讀