本题是基础bfs的基础入门,宽度优先搜索是对树的横向遍历,按照层数的遍历,完成搜索。
这个题的特点就是通过查找任何可行的路径并把它放到一个队列里,通过一个个队列的数据往外弹出,然后完成对每一个数据的遍历,完成所有合法数据的遍历,因为这里只有一条通路,所以最终只有一个数据可以达到终点,通过返回数据,来实现路径的记录。
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n, m;
int g[N][N], d[N][N];//g[N][N]用于存储数据矩阵 d[N][N]用于存储距离
int bfs()
{
queue<PII> q;
memset(d, -1, sizeof d);
d[0][0] = 0;
q.push({ 0, 0 });
int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 };
while (q.size())
{
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 && g[x][y] == 0 && d[x][y] == -1)
{
d[x][y] = d[t.first][t.second] + 1;
q.push({ 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;
}
return code;