题意
题解
长方体当前的状态为其横、纵坐标与摆放状态组成的三元组,为了方便表示,只取长方体左上方的位置作为横、纵坐标状态, B F S BFS BFS 求解即可。
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define maxn 505
struct node
{
int x, y, s;
} s, t;
const int dx[3][4] = {{0, 0, -2, 1}, {0, 0, -1, 2}, {0, 0, -1, 1}};
const int dy[3][4] = {{1, -2, 0, 0}, {1, -1, 0, 0}, {2, -1, 0, 0}};
const int ds[3][4] = {{2, 2, 1, 1}, {1, 1, 0, 0}, {0, 0, 2, 2}};
const int _dx[4] = {0, 0, -1, 1}, _dy[4] = {-1, 1, 0, 0};
char mp[maxn][maxn];
int R, C, dis[maxn][maxn][3];
bool judge(int x, int y)
{
return 0 <= x && x < R && 0 <= y && y < C;
}
bool judge(node &t)
{
if (!judge(t.x, t.y) || mp[t.x][t.y] == '#')
return 0;
if (t.s == 0 && mp[t.x][t.y] == 'E')
return 0;
if (t.s == 1 && mp[t.x + 1][t.y] == '#')
return 0;
if (t.s == 2 && mp[t.x][t.y + 1] == '#')
return 0;
return 1;
}
void bfs()
{
memset(dis, -1, sizeof(dis));
dis[s.x][s.y][s.s] = 0;
queue<node> q;
q.push(s);
while (!q.empty())
{
node v = q.front();
q.pop();
if (v.x == t.x && v.y == t.y && v.s == t.s)
{
printf("%d\n", dis[t.x][t.y][t.s]);
return;
}
node nxt;
for (int i = 0; i < 4; ++i)
{
nxt.x = v.x + dx[v.s][i], nxt.y = v.y + dy[v.s][i], nxt.s = ds[v.s][i];
if (judge(nxt) && dis[nxt.x][nxt.y][nxt.s] == -1)
dis[nxt.x][nxt.y][nxt.s] = dis[v.x][v.y][v.s] + 1, q.push(nxt);
}
}
puts("Impossible");
}
int main()
{
while (~scanf("%d%d", &R, &C) && (R | C))
{
for (int i = 0; i < R; ++i)
scanf(" %s", mp[i]);
bool fs = 1, ft = 1;
for (int i = 0; i < R; ++i)
{
for (int j = 0; (fs || ft) && j < C; ++j)
{
if (mp[i][j] == 'O')
t.x = i, t.y = j, t.s = 0, mp[i][j] = '.', ft = 0;
else if (mp[i][j] == 'X')
{
s.x = i, s.y = j, s.s = 0, mp[i][j] = '.', fs = 0;
for (int k = 0; k < 4; ++k)
{
int nx = i + _dx[k], ny = j + _dy[k];
if (judge(nx, ny) && mp[nx][ny] == 'X')
s.x = min(s.x, nx), s.y = min(s.y, ny), s.s = (k < 2 ? 2 : 1), mp[nx][ny] = '.';
}
}
}
}
bfs();
}
return 0;
}