POJ1979 Red and Black

思路:先将图存在二维数组a[20][21]中,标记@的位置为x,y。从@处出发,不停的把邻接部分用#代替,直到图中不存在‘.’为止。

总共进行DFS次数就是答案了。4个方向对应四种状态。

代码如下:

#include<iostream>
using namespace std;
int num,w,h;
int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
char a[20][21];
void dfs(int x, int y) {
    num++;
    a[x][y] = '#';
    for (int i = 0;i < 4;i++) {
        int nx = x + dx[i], ny = y + dy[i];
        if (0 <= nx&&nx < h && 0 <= ny&&ny < w&&a[nx][ny] == '.')
            dfs(nx, ny);
    }
    return;
}
int main() {
    while (cin >> w >> h) {
        if (w == 0 && h == 0)
            break;
        int x, y;num = 0;
        for(int i=0;i<h;i++)
            for (int j = 0;j < w;j++) {
                cin >> a[i][j];
                if (a[i][j] == '@') {
                    x = i;y = j;
                }
            }
        dfs(x, y);
        cout << num << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Z20161001/article/details/83662037