bfs
标准广搜题,主要是把每一步可能的坐标都先预处理出来,会好写很多
每个状态对应三个限制条件,x坐标、y坐标、lie=0表示直立在(x,y),lie=1表示横着躺,左半边在(x,y),lie=2表示竖着躺,上半边在(x,y)
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
char g[505][505];
struct rec { int x, y, lie; } st, ed;
int r, c;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
int f[505][505][3];
const int nextx[3][4] = {{-2, 1, 0, 0}, {-1, 1, 0, 0}, {-1, 2, 0, 0}};
const int nexty[3][4] = {{0, 0, -2, 1}, {0, 0, -1, 2}, {0, 0, -1, 1}};
const int nextlie[3][4] = {{2, 2, 1, 1}, {1, 1, 0, 0}, {0, 0, 2, 2}};
bool inArea(int x, int y){
return x >= 0 && x < r && y >= 0 && y < c;
}
bool valid(const rec &next){
int x = next.x, y = next.y, lie = next.lie;
if(!inArea(x, y)) return false;
if(g[x][y] == '#') return false;
if(lie == 0 && g[x][y] == 'E') return false;
if(lie == 1 && g[x][y + 1] == '#') return false;
if(lie == 2 && g[x + 1][y] == '#') return false;
return true;
}
void init(){
for(int i = 0; i < r; i ++){
for(int j = 0; j < c; j ++){
if(g[i][j] == 'O')
ed.x = i, ed.y = j, ed.lie = 0, g[i][j] = '.';
if(g[i][j] == 'X'){
bool flag = false;
for(int d = 0; d < 4; d ++){
int nx = i + dx[d];
int ny = j + dy[d];
if(inArea(nx, ny) && g[nx][ny] == 'X'){
st.x = min(i, nx), st.y = min(j, ny);
st.lie = d < 2 ? 1 : 2;
g[nx][ny] = g[i][j] = '.';
flag = true;
}
}
if(!flag){
st.x = i, st.y = j, st.lie = 0;
g[i][j] = '.';
}
}
}
}
}
int bfs(){
memset(f, -1, sizeof f);
queue<rec> q;
f[st.x][st.y][st.lie] = 0;
q.push(st);
while(!q.empty()){
rec cur = q.front(); q.pop();
//cout << cur.x << " " << cur.y << endl;
for(int i = 0; i < 4; i ++){
rec next;
next.x = cur.x + nextx[cur.lie][i];
next.y = cur.y + nexty[cur.lie][i];
next.lie = nextlie[cur.lie][i];
if(valid(next) && f[next.x][next.y][next.lie] == -1){
f[next.x][next.y][next.lie] = f[cur.x][cur.y][cur.lie] + 1;
if(next.x == ed.x && next.y == ed.y && next.lie == ed.lie)
return f[next.x][next.y][next.lie];
q.push(next);
}
}
}
return -1;
}
int main(){
while(scanf("%d%d", &r, &c) != EOF && r && c){
for(int i = 0; i < r; i ++) scanf("%s", g[i]);
init();
int ans = bfs();
if(ans == -1) printf("Impossible\n");
else printf("%d\n", ans);
}
return 0;
}