迷宫最短路径

本文介绍了一种基于广度优先搜索的迷宫寻路算法,该算法能够在给定的0-1矩阵中寻找从左上角到右下角的最短路径。详细解释了算法流程,并提供了完整的C++实现代码。
Description

为了测试某种药物对小白鼠方向感的影响,生物学家在实验室做了一个矩形迷宫,入口和出口都确定为唯一的,且分布在矩形的不同边上。现在让你算出小白鼠最短需要走多少步,才可以从入口走到出口。

Input

N+1行,第一行为NN=0表示输入结束),以下NN0-1矩阵,1表示不能通过0表示可以通过左上角和右下角为0,即入口和出口),其中N<30

Output

只有一个数,为最少要走的格子数。0表示没有路径。

Sample Input
 Copy sample input to clipboard
5
0 1 1 1 1
0 0 1 1 1
1 0 0 0 1
1 1 1 0 1
1 1 1 0 0
4
0 0 1 1
0 0 0 1
1 1 1 1
1 1 1 0
0
Sample Output
9

0


#include <iostream>
#include <queue>
#include <string.h>
#define INF 100000
using namespace std;

int str[35][35];
bool visit[35][35];
bool havePath;
int shortest[35][35];
int n;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};

bool canVisit(int x, int y) {
    if (str[y][x] == 0 && visit[y][x] == false && 0 <= x && x < n &&  0 <= y && y < n) {
        return true;
    }
    return false;
}

void initial() {
    memset(visit, 0, sizeof(visit));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            shortest[i][j] = INF;
        }
    }
    havePath = false;
}

int main(void) {
    while (cin >> n && n != 0) {
        initial();
        queue<pair<int, int> > q;
        q.push(make_pair(0, 0));
        visit[0][0] = true;
        shortest[y][x] = 1;
        while (!q.empty()) {
            int x = q.front().first;
            int y = q.front().second;
            if (x == n - 1 && y == n - 1) {
                len++;
                havePath = true;
                break;
            }
            for (int i = 0; i < 4; i++) {
                int new_x = x + dx[i];
                int new_y = y + dy[i];
                if (canVisit(new_x, new_y)) {
                    q.push(make_pair(new_x, new_y));
                    shortest[new_y][new_x] = shortest[y][x] + 1;
                }
            }
            visit[y][x] = true;
            q.pop();
        }
        if (havePath) {
            cout << shortest[n - 1][n - 1] << endl;
        } else {
            cout << "0" <<  endl;
        }
        while (!q.empty()) q.pop();
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值