题解:AT_abc420_d [ABC420D] Toggle Maze
william1118 · · 题解
思路
由于每次经过开关时状态会改变,普通最短路行不通,因此我们考虑扩充维度,把当前开关的状态(开或关)也一起记录下来,然后分类讨论进行转移(我们认为初始时开关是关的)。
具体的,当前格子不是开关的时候:
- 如果当前开关状态是关的,下一步只能走到
.或o - 否则下一步只能走到
.或x。
当前格子是开关的时候:
- 如果当前开关状态是关的,那么此时开关就会打开,下一步只能走到
.或x - 否则开关就会关闭,下一步只能走到
.或o。
然后把开关状态扔进队列里面,跑最短路即可。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 501, dr[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
// d数组和标记数组b都要扩充维度,v数组记录哪些格子是开关
int n, m, sx, sy, ex, ey, b[N][N][2], d[N][N][2], v[N][N];
char a[N][N];
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
if (a[i][j] == '?') v[i][j] = 1;
a[i][j] == 'S' && (sx = i, sy = j);
a[i][j] == 'G' && (ex = i, ey = j);
}
}
queue<array<int, 3>> q;
fill(d[0][0], d[n][m + 1], 1e9);
d[sx][sy][0] = 0;//默认初始时开关关闭
q.push({sx, sy, 0});
while (q.size()) {
int x = q.front()[0], y = q.front()[1], o = q.front()[2];//o为开关状态
q.pop();
if (b[x][y][o]) continue;
b[x][y][o] = 1;
for (int i = 0; i < 4; i++) {
int nx = x + dr[i][0], ny = y + dr[i][1];
if (nx < 1 || nx > n || ny < 1 || ny > m) continue;
if (!v[x][y] && a[nx][ny] != '#' && (!o && a[nx][ny] != 'x' || o && a[nx][ny] != 'o') && d[nx][ny][o] > d[x][y][o] + 1) {//非开关格子
d[nx][ny][o] = d[x][y][o] + 1;
q.push({nx, ny, o});
} else if (v[x][y] && a[nx][ny] != '#' && (!o && a[nx][ny] != 'o' || o && a[nx][ny] != 'x') && d[nx][ny][o ^ 1] > d[x][y][o] + 1) {//开关格子
d[nx][ny][o ^ 1] = d[x][y][o] + 1;
q.push({nx, ny, o ^ 1});
}
}
}
int ans = min(d[ex][ey][0], d[ex][ey][1]);
cout << (ans == 1e9 ? -1 : ans);
return 0;
}
- AC记录。