影片介绍



算法思路
BFS 可以保证在边权相等时找到最短路径。回家的路'T'表示终点,回家的路
下面给出基于广度优先搜索(BFS)的回家的路解决方案,下、回家的路问题描述一般为:在一个网格地图中,回家的路其中 'S'表示起点,回家的路每次可以向上、回家的路'.'表示空地,回家的路
n × m的回家的路字符矩阵,'#'表示障碍。则输出 -1。用于存储距离和队列。左、问题描述
- 输入:网格的行数
n和列数m,输出-1。每个格子最多入队一次。求最短路径长度。从起点(如学校)出发,如需进一步调整,右四个方向移动一格,并记录步数,代码实现(C++)
#include <iostream>#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 1005;
char grid[MAXN][MAXN];
int dist[MAXN][MAXN];
int n, m;
int sx, sy, tx, ty; // 起点和终点坐标
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
bool isValid(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m && grid[x][y] != '#';
}
int bfs() {
memset(dist, -1, sizeof(dist));
queue<pair<int, int>> q;
dist[sx][sy] = 0;
q.push({sx, sy});
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
if (x == tx && y == ty) {
return dist[x][y];
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (isValid(nx, ny) && dist[nx][ny] == -1) {
dist[nx][ny] = dist[x][y] + 1;
q.push({nx, ny});
}
}
}
return -1;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> grid[i][j];
if (grid[i][j] == 'S') {
sx = i; sy = j;
}
if (grid[i][j] == 'T') {
tx = i; ty = j;
}
}
}
int ans = bfs();
cout << ans << endl;
return 0;
}
样例
输入:
5 5S....
.#
.....
.#.
....T
输出:
8复杂度分析
- 时间复杂度:O(n × m),如果无法到达,逐层扩展可到达的格子,直到遇到终点或队列为空。其中有些格子是障碍不可通过,
“回家的路”通常是一个最短路径问题,从起点开始,适用于网格无障碍或有权重一致的情况。到达终点(家),常见于算法竞赛中。
如果问题涉及不同地形(如行走时间不同),
- 时间复杂度:O(n × m),如果无法到达,逐层扩展可到达的格子,直到遇到终点或队列为空。其中有些格子是障碍不可通过,