一道有趣的搜索题,用广搜比较好。注意记录状态即可, 然后更新好标记数组。每次是根据方块左上角的坐标来进行操作的。
判断能不能走的时候一定要注意占两个格的情况,到达终点时一定是竖起来才行,薄弱地带一定不能竖起来。
队列可以用STL 也可以用数组,不过用数组的话,交到G++上,可以优化到700ms或者更少
/*
ID: sdj22251
PROG: subset
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define LOCA
using namespace std;
int n, m;
char s[505][505];
bool v[505][505][5];
int move[4][2][4] = {{{0, 0, 0, 0},{0, 0, 0, 0}},
{{0, 0, -2, 1},{1, -2, 0, 0}},
{{-1, 1, 0, 0},{0, 0, -1, 2}},
{{0, 0, -1, 2},{-1, 1, 0, 0}}
};
struct wwj
{
int x, y, con, num;
wwj() {}
wwj(int a, int b, int c, int d)
{
x = a;
y = b;
con = c;
num = d;
}
}q[505* 505 * 3];
bool check(wwj x)
{
if(x.x >= n || x.y >= m || x.x < 0 || x.y < 0)
return false;
if(x.con == 1)
{
if(s[x.x][x.y] == '#')
return false;
}
else if(x.con == 2)
{
if(x.y + 1 >= m || s[x.x][x.y + 1] == '#' || s[x.x][x.y] == '#')
return false;
}
else if(x.con == 3)
{
if(x.x + 1 >= n || s[x.x][x.y] == '#' || s[x.x + 1][x.y] == '#')
return false;
}
return true;
}
int main()
{
#ifdef LOCAL
freopen("subset.in","r",stdin);
freopen("subset.out","w",stdout);
#endif
int i, j, start_row, end_row, start_clu, end_clu, con;
while(scanf("%d%d", &n, &m) != EOF)
{
if(n == 0 && m == 0) break;
memset(v, 0, sizeof(v));
con = 0;
for(i = 0; i < n; i++)
scanf("%s", s[i]);
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
if(s[i][j] == 'X')
{
if(!con)
{
start_row = i;
start_clu = j;
con = 1;
}
else if(start_clu + 1 == j)
con = 2;
else con = 3;
}
if(s[i][j] == 'O')
{
end_row = i;
end_clu = j;
}
}
}
int head = 0, tail = 0;
wwj A(start_row, start_clu, con, 0);
q[tail++] = A;
v[A.x][A.y][A.con] = true;
int ans = -1;
while(head < tail)
{
A = q[head++];
if(A.x == end_row && A.y == end_clu && A.con == 1)
{
ans = A.num;
break;
}
for(i = 0; i < 4; i++)
{
int tx = A.x + move[A.con][0][i];
int ty = A.y + move[A.con][1][i];
int tcon = A.con;
int tnum = A.num + 1;
if(tcon == 1 && i < 2)
tcon = 2;
else if(tcon == 1 && i >= 2)
tcon = 3;
else if(tcon == 2 && i >= 2)
tcon = 1;
else if(tcon == 3 && i >= 2)
tcon = 1;
wwj B(tx, ty, tcon, tnum);
if(check(B) && !v[tx][ty][tcon])
{
if(s[tx][ty] == 'E')
{
if(tcon != 1)
{
q[tail++] = B;
v[B.x][B.y][B.con] = true;
}
}
else
{
q[tail++] = B;
v[B.x][B.y][B.con] = true;
}
}
}
}
if(ans != -1)
printf("%d\n", ans);
else puts("Impossible");
}
return 0;
}