Description
为了测试某种药物对小白鼠方向感的影响,生物学家在实验室做了一个矩形迷宫,入口和出口都确定为唯一的,且分布在矩形的不同边上。现在让你算出小白鼠最短需要走多少步,才可以从入口走到出口。
Input
共N+1行,第一行为N(N=0表示输入结束),以下N行N列0-1矩阵,1表示不能通过,0表示可以通过(左上角和右下角为0,即入口和出口),其中N<30。
Output
只有一个数,为最少要走的格子数。0表示没有路径。
Sample Input
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
90
#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();
}
}
本文介绍了一种基于广度优先搜索的迷宫寻路算法,该算法能够在给定的0-1矩阵中寻找从左上角到右下角的最短路径。详细解释了算法流程,并提供了完整的C++实现代码。
2097

被折叠的 条评论
为什么被折叠?



