uva 784 - Maze Exploration

本文详细介绍了如何使用广度优先搜索(BFS)算法解决UVA在线评测平台上的迷宫探索问题,包括迷宫的初始化、节点的遍历以及输出填充后的迷宫。
// uva 784 - Maze Exploration
// 题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=105&page=show_problem&problem=725
// 题目大意:一个迷宫,人在*的地方,X是墙壁,将所有能到达的地方填充为#
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
struct Node{
    int x, y;
} now_node;
queue<Node> node_que;
int direction[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
char map[40][100];
bool visit[40][100];
int cnt_case;
int row, column;
void BFS();
bool Inmap(Node);
void Init();
int main(){
    cin >> cnt_case;
    getchar();
    while(cnt_case--){
        Init();
        while (gets(map[row++])) {
            if(map[row - 1][0] == '_')
                break; 
            if(column < strlen(map[row]))
                column = strlen(map[row]);
        }
        row--;
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < strlen(map[i]); j++)
                if(map[i][j] == '*'){
                    now_node.x = i;
                    now_node.y = j;
                    BFS();
                }
        }
        for(int i = 0; i <= row; i++){
            for(int j = 0; j < strlen(map[i]); j++){
                if (visit[i][j])
                    cout << '#';
                else 
                    cout << map[i][j];
            }
            cout << endl;
        }
    }
    return 0;
}
void Init(){
    memset(map, 0, sizeof(map));
    memset(visit, 0, sizeof(visit)); 
    row = 0;
}
void BFS(){
    Node tmp_node;
    node_que.push(now_node);
    visit[now_node.x][now_node.y] = true;
    while(node_que.size()){
        now_node = node_que.front();
        node_que.pop();
        for(int i = 0; i < 4; i++){
            tmp_node.x = now_node.x + direction[i][0];
            tmp_node.y = now_node.y + direction[i][1];
            if(Inmap(tmp_node) && map[tmp_node.x][tmp_node.y] != 'X' && !visit[tmp_node.x][tmp_node.y]){
                visit[tmp_node.x][tmp_node.y] = true;
                node_que.push(tmp_node);
            }
        }
    }
}
bool Inmap(Node node){
    return node.x >= 0 && node.y >= 0 && node.x < row && node.y < strlen(map[node.x]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值