POJ 1979 Red and Black dfs 难度:0

http://poj.org/problem?id=1979

#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 21;
bool vis[maxn][maxn];
char maz[maxn][maxn];
int n,m;
const int dx[4] = {1,-1,0,0};
const int dy[4] = {0,0,1,-1};
int ans;

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

void dfs(int x,int y)
{
    for(int i = 0;i < 4;i++)
    {
        int tx = x + dx[i],ty = y + dy[i];
        if(in(tx,ty) && !vis[tx][ty] && maz[tx][ty] != '#')
        {
            ans++;
            vis[tx][ty] = true;
            dfs(tx,ty);
        }
    }
}

int main(){
    while(scanf("%d%d",&m,&n) == 2 && (m || n))
    {
        ans = 0;
        memset(vis,0,sizeof vis);
        for(int i = 0;i < n; i++)
        {
            scanf("%s",maz[i]);
        }
        for(int x = 0;x < n; x++)
        {
            for(int y = 0;y < m;y++)
            {
                if(!vis[x][y] && maz[x][y] == '@')
                {
                    ans++;
                    vis[x][y] = true;
                    dfs(x,y);
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2015-06-05 21:20  雪溯  阅读(128)  评论(0编辑  收藏  举报