1、矩阵走迷宫问题描述
给定一个只有 0 和 1 的矩阵,0 代表障碍物,1 代表可以通过。求从起点 B 到终点 E 的最短路径。
输入:
第一行:两个数字 n 、m,代表矩阵大小;
接下来 n 行:代表矩阵输入;
接下来一行:代表起点坐标;
最后一行:代表终点坐标。
输出:
从起点到终点的最短路径。
如果路径不存在,则输出-1;如果存在,则输出最短路径长度。
2、敲代码
(1)思路
BFS,访问过的就标记为障碍,每一次从4个方向找一个没有障碍的进队。最终层数就是最短路径。
(2)
/*
输入
4 5
1 0 1 1 1
1 0 1 0 1
1 1 1 0 1
0 0 0 0 1
0 0
3 4
输出
12
输入
4 5
1 0 1 1 1
1 0 1 0 1
1 1 1 0 1
0 0 0 0 1
2 1
3 4
输出
9
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main() {
//input
int n, m;
cin >> n >> m;
vector<vector<int>> nums(n, vector<int>(m));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> nums[i][j];
int bx, by; //起点
int ex, ey; //终点
cin >> bx >> by;
cin >> ex >> ey;
//起点终点判断
if (nums[bx][by] == 0 || nums[ex][ey] == 0){
cout << -1 << endl;
return 0;
}
//bfs
queue<pair<int, int>> q;
q.push({ bx, by }); //起点进队
nums[bx][by] = 0; //已访问,设为障碍
int cnt = 0;
static int a[5] = { 0, 1, 0, -1, 0 };
while (!q.empty()) {
int qs = q.size();
cnt++;
while (qs--) {
auto qf = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int x = qf.first + a[i];
int y = qf.second + a[i + 1];
if (x < 0 || x >= n || y < 0 || y >= m) continue; //越界
if (nums[x][y] == 0) continue; //障碍
//终点
if (x == ex && y == ey) {
cout << cnt + 1; //加1,包括起点;不加1,不包括起点
return 0;
}
q.push({ x, y }); //进队
nums[x][y] = 0; //访问标记
}
}
}
cout << -1 << endl;
return 0;
}