bfs。100*100的地图上,有4种钥匙,可能有多个或没有出口,可能有钥匙没门,也可能有门没钥匙。压缩一下,三维数组判重。
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<cmath>
///LOOP
#define REP(i, n) for(int i = 0; i < n; i++)
#define FF(i, a, b) for(int i = a; i < b; i++)
#define FFF(i, a, b) for(int i = a; i <= b; i++)
#define FD(i, a, b) for(int i = a - 1; i >= b; i--)
#define FDD(i, a, b) for(int i = a; i >= b; i--)
///INPUT
#define RI(n) scanf("%d", &n)
#define RII(n, m) scanf("%d%d", &n, &m)
#define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k)
#define RIV(n, m, k, p) scanf("%d%d%d%d", &n, &m, &k, &p)
#define RV(n, m, k, p, q) scanf("%d%d%d%d%d", &n, &m, &k, &p, &q)
#define RFI(n) scanf("%lf", &n)
#define RFII(n, m) scanf("%lf%lf", &n, &m)
#define RFIII(n, m, k) scanf("%lf%lf%lf", &n, &m, &k)
#define RFIV(n, m, k, p) scanf("%lf%lf%lf%lf", &n, &m, &k, &p)
#define RS(s) scanf("%s", s)
///OUTPUT
#define PN printf("\n")
#define PI(n) printf("%d\n", n)
#define PIS(n) printf("%d ", n)
#define PS(s) printf("%s\n", s)
#define PSS(s) printf("%s ", n)
#define PC(n) printf("Case %d: ", n)
///OTHER
#define PB(x) push_back(x)
#define CLR(a, b) memset(a, b, sizeof(a))
#define CPY(a, b) memcpy(a, b, sizeof(b))
#define display(A, n, m) {REP(i, n){REP(j, m)PIS(A[i][j]);PN;}}
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int MOD = 9901;
const int INFI = 1e9 * 2;
const LL LINFI = 1e17;
const double eps = 1e-6;
const double pi = acos(-1.0);
const int N = 111;
const int M = 1111;
const int move[8][2] = {0, 1, 0, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 1, -1, -1};
struct point
{
int x, y, k, t;
point(){};
point(int a, int b, int c, int d){x = a, y = b, k = c, t = d;};
}p;
int n, m, mm[255] = {0};
char s[N][N];
bool vis[N][N][16];
queue<point> q;
bool check(int x, int y)
{
return x < n && y < m && x >= 0 && y >= 0;
}
void bfs()
{
int tx, ty, key;
while(!q.empty())
{
p = q.front();
q.pop();
REP(i, 4)
{
tx = p.x + move[i][0];
ty = p.y + move[i][1];
if(check(tx, ty) && !vis[tx][ty][p.k] && s[tx][ty] != '#')
{
if(s[tx][ty] == 'X')
{
printf("Escape possible in %d steps.\n", p.t + 1);
return ;
}
else if(s[tx][ty] == '.')
{
vis[tx][ty][p.k] = 1;
q.push(point(tx, ty, p.k, p.t + 1));
}
else if(s[tx][ty] >= 'A' && s[tx][ty] <= 'Z')
{
if(p.k & mm[s[tx][ty]])
{
vis[tx][ty][p.k] = 1;
q.push(point(tx, ty, p.k, p.t + 1));
}
}
else
{
key = (p.k | mm[s[tx][ty]]);
vis[tx][ty][p.k] = 1;
q.push(point(tx, ty, key, p.t + 1));
}
}
}
}
puts("The poor student is trapped!");
}
int main()
{
//freopen("input.txt", "r", stdin);
mm['B'] = mm['b'] = 1;
mm['Y'] = mm['y'] = 2;
mm['R'] = mm['r'] = 4;
mm['G'] = mm['g'] = 8;
while(RII(n, m), n + m)
{
CLR(vis, 0);
while(!q.empty())q.pop();
REP(i, n)
{
RS(s[i]);
REP(j, m)
{
if(s[i][j] == '*')
{
s[i][j] = '.';
vis[i][j][0] = 1;
q.push(point(i, j, 0, 0));
}
}
}
bfs();
}
return 0;
}