基本思想:
宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型。其别名又叫BFS,属于一种盲目搜寻法,目的是系统地展开并检查图中的所有节点,以找寻结果。换句话说,它并不考虑结果的可能位置,彻底地搜索整张图,直到找到结果为止。简单来说,bfs好像是一个耳听六路眼观八方的人,搜索时是一层一层的搜索的。BFS利用的数据结构是queue,空间复杂度为o(2^n)。BFS是一个从近到远的扩散过程,所以与dfs搜索目标点不同的是,dfs不一定是最短的距离,而bfs是搜索到该点的距离,因为我们可以将bfs的搜索过程看作湖面上丢下一块石子,向外不断扩散搜索的过程。
如图是走迷宫的样例,从左上角开始搜索,1是墙壁,0上的数字表示第几层的遍历,遍历到目标点为第八层,即走到目标点的最短距离就是8
给定一个 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
#include<iostream> #include<cstring> #include<algorithm> #include<queue> using namespace std; typedef pair<int, int> PII; const int N=110; int n, m; int a[N][N], b[N][N]; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; void bfs() { memset(b, -1, sizeof b); queue<PII> q; b[0][0] = 0; q.push({0, 0}); while(!q.empty()) { auto t = q.front(); q.pop(); 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 && a[x][y] == 0 && b[x][y] == -1) { q.push({x, y}); b[x][y] = b[t.first][t.second] + 1; } } } } int main() { cin >> n >> m; for(int i = 0; i < n; i++) for(int j = 0;j < m; j++) cin >> a[i][j]; bfs(); cout << b[n - 1][m - 1]; return 0; }
例题: