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
9 0
#include <iostream>
#include <queue>
using namespace std;
int arr[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; //定义四个方向
struct Node {
int x;
int y;
int step;
Node(int x1, int y1, int step1) : x(x1), y(y1), step(step1) { }
};
int BFS(int n, int *maze) {
int *p = new int[n*n];
for (int i = 0; i < n*n; ++i) p[i]= 0; //如果没有经过则为0,经过则为1
queue<Node> q;
Node node(0, 0, 1);
q.push(node);
while (!q.empty()) {
node = q.front();
q.pop();
//上下左右都走一遍
if (node.x == n-1 && node.y == n-1) { delete p; return node.step;}
p[node.x*n+node.y] = 1;
for (int i = 0; i < 4; ++i) {
int x = node.x + arr[i][0];
int y = node.y + arr[i][1];
if (x >= 0 && y >= 0 && x < n && y < n && p[x*n+y] == 0 && maze[x*n+y] == 0) {
p[x*n+y] = 1;
Node next(x, y, node.step + 1);
q.push(next);
}
}
}
delete p;
return -1;
}
int main()
{
int n;
int all_step;
while (cin >> n) {
if (n == 0) { return 0;}
int *maze = new int[n*n];
for (int i = 0; i < n*n; ++i ) {
cin >> maze[i];
}
if (n == 1 && maze[0] == 1) {
cout << 0 << endl;
return 0;
}
all_step = 0;
all_step = BFS(n, maze);
if (all_step == -1) {
cout << "0" << endl;
} else cout << all_step << endl;
delete maze;
system ("pause");
}
return 0;
}
本文介绍了一种使用广度优先搜索(BFS)算法解决迷宫寻路问题的方法,旨在找到从起点到终点的最短路径。文章提供了一个具体的C++实现示例,包括输入输出格式及样本测试案例。
Copy sample input to clipboard
2071

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



