BFS——广度优先算法(Breadth First Search)
问题描述
给定一个 n×m的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1 ,其中 0 表示可以走的路,1 表示不可通过的墙壁。最初,有一个人位于左上角 (1,1)处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。请问,该人从左上角移动至右下角 (n,m)处,至少需要移动多少次。
输入格式
第一行包含两个整数 n 和 m。
接下来 n 行,每行包含 m个整数( 0 或 1 ),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
输入样例:
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
#include <iostream>
#include<queue>
#define INF 0x3f3f3f3f//INF表示不可达
using namespace std;
queue<pair<int, int>> q;
const int N = 1e3 + 5;
int a[N][N];//表示迷宫
int dst[N][N];//保存距离
int n, m;//n行,m列
bool check(int x, int y)//检查是否可达
{
if (x > 0 && x <= n && y > 0 && y <= m && a[x][y] == 0) return true;
else return false;
}
void bfs(int x, int y)
{
dst[x][y] = 0;//起点距离为0
q.push({ x,y });
while (!q.empty())
{
x = q.front().first;
y = q.front().second;
q.pop();
if (check(x, y + 1))//往右走
{
if (dst[x][y + 1] > dst[x][y] + 1)
{
dst[x][y + 1] = dst[x][y] + 1;//距离更新
q.push({ x,y + 1 });
//把距离更新的点加入队列中,看能否通过这个点把周围的点距离继续更新
//根据队列先进先出的性质,第一次更新时的距离一定是最短距离
}
}
if (check(x, y - 1))//往左走
{
if (dst[x][y - 1] > dst[x][y] + 1)
{
dst[x][y - 1] = dst[x][y] + 1;
q.push({ x,y - 1 });
}
}
if (check(x + 1, y))//往下走
{
if (dst[x + 1][y] > dst[x][y] + 1)
{
dst[x + 1][y] = dst[x][y] + 1;
q.push({ x + 1,y });
}
}
if (check(x - 1, y))//往上走
{
if (dst[x - 1][y] > dst[x][y] + 1)
{
dst[x - 1][y] = dst[x][y] + 1;
q.push({ x - 1,y });
}
}
}
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
scanf("%d", &a[i][j]);
dst[i][j] = INF;//初始化距离数组
}
bfs(1, 1);
printf("%d", dst[n][m]);
return 0;
}