题目链接
http://poj.org/problem?id=3322
分析
每次操作,地图不会改变,变化的坐标及放置方式可以设为状态,进行BFS。
预处理出各种放置方式下,向各个方向移动后状态的变化情况。
AC代码
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 505;
const int nxt[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
const int next_x[3][4] = {{0, -2, 0, 1}, {0, -1, 0, 1}, {0, -1, 0, 2}};
const int next_y[3][4] = {{-2, 0, 1, 0}, {-1, 0, 2, 0}, {-1, 0, 1, 0}};
const int next_z[3][4] = {{1, 2, 1, 2}, {0, 1, 0, 1}, {2, 0, 2, 0}};
struct State {
int x, y, z;
bool operator == (const State& rhs) const {
return x == rhs.x && y == rhs.y && z == rhs.z;
}
} st, ed;
int n, m, d[maxn][maxn][3];
char map[maxn][maxn];
queue<State> q;
inline int judge(int x, int y) {
return x >= 1 && x <= n && y >= 1 && y <= m;
}
inline int judge(State s) {
if (!judge(s.x, s.y)) return 0;
if (map[s.x][s.y] == '#') return 0;
if (!s.z && map[s.x][s.y] != '.') return 0;
if (s.z == 1 && map[s.x][s.y + 1] == '#') return 0;
if (s.z == 2 && map[s.x + 1][s.y] == '#') return 0;
return 1;
}
inline int bfs() {
memset(d, -1, sizeof(d));
while (!q.empty()) q.pop();
d[st.x][st.y][st.z] = 0;
q.push(st);
while (!q.empty()) {
State s = q.front(), ns;
q.pop();
if (s == ed) return d[s.x][s.y][s.z];
for (int i = 0; i < 4; ++i) {
ns.x = s.x + next_x[s.z][i];
ns.y = s.y + next_y[s.z][i];
ns.z = next_z[s.z][i];
if (!judge(ns)) continue;
if (d[ns.x][ns.y][ns.z] == -1) {
d[ns.x][ns.y][ns.z] = d[s.x][s.y][s.z] + 1;
q.push(ns);
}
}
}
return 0;
}
int main() {
while (scanf("%d%d", &n, &m) == 2 && !(!n && !m)) {
for (int i = 1; i <= n; ++i) scanf("%s", map[i] + 1);
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
if (map[i][j] == 'O')
ed.x = i, ed.y = j, ed.z = 0, map[i][j] = '.';
else if (map[i][j] == 'X') {
for (int k = 2; k < 4; ++k) {
int x = i + nxt[k][0], y = j + nxt[k][1];
if (judge(x, y) && map[x][y] == 'X') {
st.x = i, st.y = j, st.z = k - 1;
map[i][j] = map[x][y] = '.';
break;
}
}
if (map[i][j] == 'X')
st.x = i, st.y = j, st.z = 0, map[i][j] = '.';
}
}
int ans = bfs();
if (ans) printf("%d\n", ans);
else printf("Impossible\n");
}
return 0;
}