poj1979 Red And Black(DFS)

题目链接

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

思路

floodfill问题,使用dfs解决

代码

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

const int N = 20;
char maze[N][N];
int visit[N][N];
int dir[4][2] = {{-1, 0}, {0 ,1}, {1, 0}, {0, -1}};
int nums;
int w, h;

void dfs(int r, int c){
    visit[r][c] = 1;
    for(int i=0; i<4; i++){
        int nextr = r + dir[i][0];
        int nextc = c + dir[i][1];

        if(nextr>=0 && nextr<h && nextc>=0 && nextc<w && maze[nextr][nextc]!='#' && !visit[nextr][nextc]){
            visit[nextr][nextc] = 1;
            nums++;
            dfs(nextr, nextc);
        }
    }
}

int main(){
    //freopen("poj1979.txt", "r", stdin);
    int sr, sc;
    while(cin>>w>>h && w && h){
        nums = 1;
        memset(visit, 0, sizeof(visit));
        for(int i=0; i<h; i++){
            for(int j=0; j<w; j++){
                cin>>maze[i][j];
                if(maze[i][j] == '@'){
                    sr = i;
                    sc = j;
                }
            }
        }
        dfs(sr, sc);
        cout << nums <<endl;
    }
    return 0;
}
posted @ 2017-11-03 11:09  ColdCode  阅读(144)  评论(0编辑  收藏  举报
AmazingCounters.com