POJ NO.1979 Red and Black(DPS,搬黑砖,,,)

来源:互联网 发布:事业单位网站域名 编辑:程序博客网 时间:2024/06/07 01:03

问题描述:

一个广场由黑砖和红砖组成,给你一个起点看你(起点算是黑砖)能办多少黑砖。

题目链接:点击打开链接

思路

问题转换 ----> 把所有能到达的 ‘ . ’(黑砖)全换成某个字符(如‘ e ’);

先找到起点,题目中没给出需要自己遍历数组找到,然后以此为起点,进行替换(把‘ . ’换成‘ e ’要用到DFS);

最后再遍历数组计算出所有的‘ e ’的个数即可。


代码:

#include<iostream>#include<cstdio>using namespace std;const int MAX = 10086;int W, H;//列数和行数char field[MAX][MAX];int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};//移动的四个方向void DFS(int x, int y);int main(){    while(~scanf("%d%d", &W, &H)){        int m, n, cnt = 0;        if(W == 0 && H == 0) break;        for(int i = 0; i < H; i++)            scanf("%s", field[i]);        //找到开始的坐标        for(int i = 0; i < H; i++)            for(int j = 0; j < W; j++){                if(field[i][j] == '@'){                    m = i, n = j;            }        }        DFS(m, n);//进行替换        for(int i = 0; i < H; i++)            for(int j = 0; j < W; j++)                if(field[i][j] == 'e')                cnt++;        cout << cnt << endl;    }    return 0;}void DFS(int x, int y){        field[x][y] = 'e';    for(int i = 0; i < 4; i++){        //nx, ny分别代表移动后的坐标        int nx = x + dx[i], ny = y + dy[i];    if(0 <= nx && nx < H && 0 <= ny && ny < W &&       field[nx][ny] == '.'){           DFS(nx, ny);       }    }}


1 0