#include<iostream>#include<cstring>#include<queue>usingnamespace std;
typedef pair<int, int> PII;
constint N = 100 + 10;
int n, m;
int g[N][N], d[N][N];
queue<PII> q;
intbfs(){
q.push({0, 0});
memset(d, -1, sizeof(d));
d[0][0] = 0;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while (q.size()) {
PII 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];
}
intmain(){
cin >> n >> m;
for (int i = 0; i < n; i ++)
for (int j = 0; j < m; j ++)
cin >> g[i][j];
cout << bfs() << endl;
return0;
}
pair<int, int> 用来记录坐标 (x, y);
使用辅助队列进行 BFS 搜索,每次取出队头元素,判断上下左右四个格子有无满足下列条件的情况,如果满足情况就入队,并把距离更新:
① x 坐标和 y 坐标都在迷宫内,没有越过边界;
② 格子是可以走的路;(g[ x ][ y ] == 0)
③ 第一次走到这个格子,才能保证最短;(d[ x ][ y ] == -1)
BFS 数组模拟队列
点击查看代码
#include<iostream>#include<cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 100 + 10;
int n, m;
int g[N][N], 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][0] = 0;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while (hh <= tt) {
PII t = q[hh ++];
for (int i = 0; i < 4; i ++) {
intx = 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;
return0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!