正经题解|走迷宫
2024-03-22 11:16:31
发布于:浙江
279阅读
0回复
0点赞
【算法分析】
求最少需要多少步,考虑使用广搜。从起点开始进行搜索,规则只能向上下左右走动,当搜索到终点时就结束。
【参考代码】
#include <bits/stdc++.h>
using namespace std;
char MAP[49][49];
bool vis[49][49];
struct node {
int x, y, step;
}l,r;
int dir[4][2] = { {-1,0} ,{0,1},{1,0},{0,-1} };
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> MAP[i] + 1;
}
queue<node> q;
q.push({ 1,1,1 });
vis[1][1] = 1;
while (q.size()) {
r = q.front();
q.pop();
if (r.x == n && r.y == m) {
cout << r.step;
break;
}
for (int i = 0; i < 4; i++) {
l.x = r.x + dir[i][0];
l.y = r.y + dir[i][1];
l.step = r.step + 1;
if (l.x >= 1 && l.x <= n && l.y >= 1 && l.y <= m && !vis[l.x][l.y] && MAP[l.x][l.y] == '.') {
vis[l.x][l.y] = 1;
q.push(l);
}
}
}
return 0;
}
【时间复杂度】
【预计得分】
全部评论 2
顶
2024-11-07 来自 江苏
0有帮助,赞一个。
2024-06-08 来自 上海
0
有帮助,赞一个