7-1 迷宫问题

小明置身于一个迷宫,请你帮小明找出从起点到终点的最短路程。
小明只能向上下左右四个方向移动。

输入格式:

第一行是两个整数n和m (1≤ m, n ≤100),表示迷宫的长和宽。接下来是n行,每行m个数字,表示整个迷宫。空地格子用0表示,障碍物用1表示,小明所在起点用3表示,终点用4表示。

输出格式:

如果能够到达终点,输出一个整数,表示小明从起点到目的地所需的最短时间。如果不能到达终点,输出“unreachable”。

输入样例1:

5 5
1 0 1 1 1
1 0 4 1 0
1 0 0 1 0
0 0 0 1 0
1 0 3 0 1

输出样例1:

3

输入样例2:

5 5
3 0 1 1 1
1 0 1 1 0
1 0 1 1 0
0 0 0 1 0
1 0 1 0 4

输出样例2:

unreachable

#include<iostream>
#include<vector>
#include<queue>
#include<utility>
using namespace std;
typedef pair<char, char> ptr;
struct Node {
    ptr start;
    int step;
};
vector<vector<char>> maze(100, vector<char>(100, '1'));
vector<vector<bool>> visited(100, vector<bool>(100, false));
vector<ptr> dir = { {1,0},{0,1},{-1,0},{0,-1} };
void bfs(ptr start, ptr end) {
    queue<Node> p;
    p.push({ start,0 });
    bool found = false;
    while (!p.empty()) {
        Node q = p.front();
        p.pop();
        if (q.start == end) {
            found = true;
            cout << q.step << endl;
            break;
        }
        for (int i = 0;i < 4;i++) {
            int tx = q.start.first + dir[i].first;
            int ty = q.start.second + dir[i].second;
            if (tx >= 0 && tx < 100 && ty >= 0 && ty < 100 && maze[tx][ty] == '0' && !visited[tx][ty]) {
                visited[tx][ty] = true;
                p.push({ {tx,ty},q.step + 1 });
            }
        }
    }
    if (!found)
        cout << "unreachable" << endl;
}
int main() {
    int n, m;
    cin >> n >> m;
    ptr start, end;
    for (int i = 0;i < n;i++) {
        for (int j = 0;j < m;j++) {
            cin >> maze[i][j];
            if (maze[i][j] == '3') {
                start = { i,j };
                maze[i][j] = '0';
            }
            if (maze[i][j] == '4') {
                end = { i,j };
                maze[i][j] = '0';
            }
        }
    }
    bfs(start, end);
    return 0;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值