level 2
#include <iostream>
#include <queue>
#define MAXSIZE 1000
using namespace std;
struct node {
int x, y, step;
} ;
int main() {
queue<struct node>q;
int j, k, o, p, ss = 0;
cin >> j >> k;
char a[MAXSIZE][MAXSIZE];
node start, final, point;
for (o = 0; o < j; o++) {
for (p = 0; p < k; p++) {
cin >> a[o][p];
if (a[o][p] == 'S') {
start.x = o;
start.y = p;
} else if (a[o][p] == 'T') {
final.x = o;
final.y = p;
a[o][p] = '.';
}
}
}
start.step= 0;
q.push(start);
while (1) {
if (q.empty()) {
break;
}
a[q.front().x][q.front().y] = '1';
if (q.front().x == final.x && q.front().y == final.y) {
cout << q.front().step;
break;
}
if (q.front().x + 1 < j) {
if (a[q.front().x + 1][q.front().y] == '.') {
point.x = q.front().x + 1;
point.y = q.front().y;
point.step= ss + 1;
q.push(point);
}
}
if (q.front().x - 1 >= 0) {
if (a[q.front().x - 1][q.front().y] == '.') {
point.x = q.front().x - 1;
point.y = q.front().y;
point.step= ss + 1;
q.push(point);
}
}
if (q.front().y + 1 < k) {
if (a[q.front().x][q.front().y + 1] == '.') {
point.x = q.front().x;
point.y = q.front().y + 1;
point.step= ss + 1;
q.push(point);
}
}
if (q.front().y - 1 >= 0) {
if (a[q.front().x][q.front().y - 1] == '.') {
point.x = q.front().x;
point.y = q.front().y - 1;
point.step= ss + 1;
q.push(point);
}
}
q.pop();
if (ss != q.front().step) {
ss++;
}
}
return 0;
}
2024年03月31日 03点03分
8
n,m 不是小于 100 吗?你多了个 0
2024年03月31日 04点03分
@✨Kiraa✨ 你少来 map 来保存已访问过的地点,可以搜索 astar 算法
2024年03月31日 04点03分
@✨Kiraa✨ 一般是将当前节点四个方向相邻的四个节点压入队列中,如果相邻节点不通或相邻节点已访问过则不需要再次压入
2024年03月31日 04点03分
level 12
1.MAXSIZE是100不是1000
2.没有标记已访问的点
2024年03月31日 04点03分
10
MAXSIZE一开始设的101也是报错,然后while循环里面第二句把二维数组对应坐标的值改成1了,那它就不符合下面if的条件了呀。
2024年03月31日 04点03分
@✨Kiraa✨ 不能在出队列的时候再标记呀,入队列的时候就应该标记了
2024年03月31日 04点03分
level 2
感谢各位大佬们,问题解决了,把标记走过这一步放在压入队列前一步就不会报错了
2024年03月31日 04点03分
13