题目描述
给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1,其中 0 表示可以走的路,1表示不可通过的墙壁。
最初,有一个人位于左上角 (1,1)处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角 (n,m)处,至少需要移动多少次。
数据保证 (1,1)处和 (n,m) 处的数字为 0,且一定至少存在一条通路。
输入格式
第一行包含两个整数 n和 m。
接下来 n行,每行包含 m 个整数(0 或 1),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
数据范围
1≤n,m≤100
输入样例:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出样例:
8
题目分析
在处理最短路径的问题,使用BFS进行解决。DFS虽然也能进行路径搜索,但找到最短路径的时间要比BFS时间长,因为BFS是一层层搜索,当找到终点时,必为最短路径。
算法实现
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 110;
/*
typedef struct position{ // 标记当前位置的坐标
int x, y;
}pos;
*/
typedef pair<int, int> pos;
int n, m; // 地图长宽
int g[N][N]; // 存储地图
int d[N][N]; // 标记搜索到的点的距离
pos recordPre[N][N];
// pos recordPre[N][N]; // 记录[i][j]位置时,上一步的下标位置
//pos q[N * N]; // 构建队列存储位置
int bfs(){
// 初始化d[N][N]
memset(d, -1, sizeof d);
d[0][0] = 0; // 从(0,0)开始出发
// 构建队列
queue<pos> q;
q.push({0, 0});
// int front = 0, rear = 0;
// q[rear++] = {0, 0}; // 将(0,0)入队
// 存储四种移动位置的情况
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while(!q.empty()){
auto e = q.front();
q.pop();
for(int i = 0; i < 4; i++){
int x = e.first + dx[i], y = e.second + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1){
d[x][y] = d[e.first][e.second] + 1;
q.push({x, y});
// 记录走过的路径
recordPre[x][y] = e;
}
}
}
// while(front < rear){ // 判断队列是否为空
// pos e = q[front++];
// for(int i = 0; i < 4; i++){ // 从四个方向进行试探
// int x = e.x + dx[i];
// int y = e.y + dy[i];
// // 在允许范围内,则进入下一步
// if(x >= 0 && y>= 0 && x < n && y < m && g[x][y] == 0 && d[x][y] == -1){
// d[x][y] = d[e.x][e.y] + 1;
// // 记录走过的路径
// //recordPre[x][y] = e;
// q[rear++] = {x, y};
// }
// }
// }
// 从(n,m)向上输出路径
// int x = n - 1, y = m - 1;
// while(x || y){
// cout << x << " " << y << endl;
// pos e = recordPre[x][y];
// x = e.first;
// y = e.second;
// //x = e.x;
// //y = e.y;
// }
return d[n - 1][m - 1];
}
int main(){
cin >> n >> m;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
cin >> g[i][j];
cout << bfs() << endl;
return 0;
}