Monsters
Monsters
题目描述
你在一个迷宫中,有怪物在追你,你不能被怪物抓到,你要跑到迷宫边缘,迷宫中有障碍,问你是否可以逃出去,若能要给出方案
思路
我想到一个格子,就必须我在怪物到达之前到那个格子才不会被抓到,所以需要求出最早怪物到达这里所需的时间,所以用搜索,可以运用 BFS 边权都是一,层数就是最短路的特性求解,求完以后就搜索自己怎么走,看是否能到达边缘,如果能记录路径中的父亲关系,从边缘用父亲关系还原整条路径,并输出答案。
代码
#include <iostream>
#include <queue>
using namespace std;
const int MaxN = 1010;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, -1, 1};
struct S {
int x, y, t;
} fa[MaxN][MaxN];
int n, m, sx, sy, now = 1, ex, ey, ans = 1e9;
char c[MaxN][MaxN];
bool flag[MaxN][MaxN];
int ttt[MaxN][MaxN], tt[MaxN][MaxN], vis[MaxN][MaxN];
queue<S> q;
void Record(S u, int x, int y, int t) {
if (x < 1 || x > n || y < 1 || y > m || vis[x][y] == now || ttt[x][y] <= t || flag[x][y]) {
return;
}
vis[x][y] = now, fa[x][y] = u;
if (now == 1) {
ttt[x][y] = t;
} else {
tt[x][y] = t;
}
q.push({x, y, t});
}
void PrintFather(int x, int y) {
if (fa[x][y].x == x && fa[x][y].y == y) {
return;
}
PrintFather(fa[x][y].x, fa[x][y].y);
if (fa[x][y].x == x + 1) {
cout << "U";
}
if (fa[x][y].x == x - 1) {
cout << "D";
}
if (fa[x][y].y == y + 1) {
cout << "L";
}
if (fa[x][y].y == y - 1) {
cout << "R";
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ttt[i][j] = tt[i][j] = 1e9;
cin >> c[i][j];
if (c[i][j] == 'M') {
Record({i, j, 0}, i, j, 0);
} else if (c[i][j] == 'A') {
sx = i, sy = j;
} else if (c[i][j] == '#') {
flag[i][j] = 1;
}
}
}
for (; !q.empty(); q.pop()) {
S u = q.front();
for (int i = 0; i < 4; i++) {
Record(u, u.x + dx[i], u.y + dy[i], u.t + 1);
}
}
now++;
for (Record({sx, sy, 0}, sx, sy, 0); !q.empty();) {
S u = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
Record(u, u.x + dx[i], u.y + dy[i], u.t + 1);
}
}
for (int i = 1; i <= n; i++) {
if (ans > tt[i][1]) {
ans = tt[i][1], ex = i, ey = 1;
}
if (ans > tt[i][m]) {
ans = tt[i][m], ex = i, ey = m;
}
}
for (int i = 1; i <= m; i++) {
if (ans > tt[1][i]) {
ans = tt[1][i], ex = 1, ey = i;
}
if (ans > tt[n][i]) {
ans = tt[n][i], ex = n, ey = i;
}
}
if (ans != 1e9) {
cout << "YES" << endl
<< ans << endl;
PrintFather(ex, ey);
} else {
cout << "NO" << endl;
}
return 0;
}
时间复杂度
搜索:
空间复杂度
记录父亲,队列等: