先来讲一下bfs(广度优先搜索)的理解和模扳;
BFS(广度优先搜索)
bfs是一个对连通图进行遍历的算法。它的思想是从一个被选定的点出发;然后从这个点的所有方向每次只走一步的走到底(即其中一个方向走完一步之后换下一个方向继续走);如果得不到目的解,那就返回事先定好的值,如果找到直接返回目的解。
如图所示,从1开始搜,有2,3,4几个点,存起来,从2开始有5,6,存起来,搜3,有7,8,存起来,搜4,没有了;现在开始搜刚刚存的点,从5开始,没有,然后搜6.。。一直进行,直到找到;
模扳
接下来看一个经典的迷宫题:
题一.ACWing 844.走迷宫
给定一个 n×mn×m 的二维整数数组,用来表示一个迷宫,数组中只包含 00 或 11,其中 00 表示可以走的路,11 表示不可通过的墙壁。
最初,有一个人位于左上角 (1,1)(1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角 (n,m)(n,m) 处,至少需要移动多少次。
数据保证 (1,1)(1,1) 处和 (n,m)(n,m) 处的数字为 00,且一定至少存在一条通路。
输入格式
第一行包含两个整数 nn 和 mm。
接下来 nn 行,每行包含 mm 个整数(00 或 11),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
数据范围
1≤n,m≤1001≤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
代码一:(数组模拟队列)
//迷宫
// 0代表可以走的路,1代表墙壁不能走
#include <iostream>
#include <algorithm>
//#include <bits/stdc++.h>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int>PII;
const int N = 110;
int n, m;
int g[N][N]; //存储地图
int d[N][N]; // 储存每一个点到起点的距离
PII q[N * N]; //手动定义一个队列
int bfs() {
int hh = 0, tt = 0;//队头&队尾
q[0] = {0, 0};
memset(d, -1, sizeof(d)); //把所有的d[0]设置为-1
d[0][0] = 0;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while (hh <= tt) { //队列里面有元素
auto t = q[hh++];
for (int i = 0; i < 4; i++) {
int x = t.first + dx[i], y = t.second + dy[i];
//判断是否在边界内,判断是否在地图内,判断是否没有走过这一步
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {
d[x][y] = d[t.first][t.second] + 1;
q[ ++tt] = {x, 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;
}
代码二:(直接使用STL)
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n, m;
// 坐标位移
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int g[N][N]; // 存原始地图
int d[N][N]; // 存每个点到起始点的距离
// PII pre[N][N]; // 输出路径用
int bfs() {
// 起点入队
queue<PII> q;
PII t = {0, 0};
q.push(t);
// 队列不为空,一直循环
while(!q.empty()) {
// 取出并保存队头
auto pp = q.front();
// 删除
q.pop();
// 四个方向循环判断一下
for(int i = 0; i < 4; i++) {
int x = pp.first + dx[i];
int y = pp.second + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {
// 记录答案
d[x][y] = d[pp.first][pp.second] + 1;
// pre[x][y] = pp; // 输出路径用
// 扩展队头
q.push({x,y});
}
}
}
// 输出路径
/*
int x = n - 1;
int y = m - 1;
while(x || y) {
cout << x << ' ' << y << endl;
auto t = pre[x][y];
x = t.first;
y = t.second;
}
*/
// 输出答案
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];
// 初始化
memset(d, -1, sizeof(d));
d[0][0] = 0;
cout << bfs() << endl;
return 0;
}