poj1979 Red and Black

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

image.png

image.png

image.png

典型的dfs
注意:将走过的路设置为"#",不需要还原回去。

//
// Created by ljs on 2018/8/27.
//
#include <iostream>
using namespace std;
int m, n;
int dir[4][4] = {{-1, 0}, {0, 1},{1, 0}, {0, -1}};
int count = 0;

void dfs(char maze[21][21], int x, int y){
    count++;
    for(int i = 0; i < 4; i++){
        int xx = x + dir[i][0];
        int yy = y + dir[i][1];
        if(xx >= 0 && xx <= m-1 && yy >= 0 && yy <= n-1 && maze[xx][yy] == '.'){
            maze[xx][yy] = '#';
            dfs(maze,xx, yy);
        }
    }
}
int main(){
    while(1){
        cin>>n>>m;
        if(m == 0 && n == 0) break;
        int startx, starty;
        char maze[21][21];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                cin>>maze[i][j];
                if(maze[i][j] == '@'){
                    startx = i;
                    starty = j;
                }
            }
        }
        maze[startx][starty] == '#';
        count = 0;
        dfs( maze, startx, starty);
        cout<<count<<endl;
    }
}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容