#include #include #include using namespace std; const int MAX = 100; int W, H; class Hr; class P { public: char klic; char dvere; bool stena; bool exit; void load(char c) { dvere = 0; klic = 0; exit = (c == 'X'); stena = (c == '#'); if (c == 'r' || c == 'g' || c == 'b' || c == 'y') klic = c; if (c == 'R' || c == 'G' || c == 'B' || c == 'Y') dvere = c - 'A' + 'a'; } }; bool used[MAX*MAX*16]; P pozice[MAX][MAX]; void nul() { for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { for (int k = 0; k < 16; k++) { used[x+MAX*y+MAX*MAX*k] = false; } } } } struct K { bool y, r, g, b; inline int toint() { return (b ? 1 : 0) + (g ? 2 : 0) + (r?4:0) + (y?8:0); } inline void fromint(int a) { b = (a & 1); g = (a & 2); r = (a & 4); y = (a & 8); } inline bool ma(char c) { switch(c) { case 'r': return r; case 'g':return g; case 'b': return b; case 'y': return y; } return false; } void dej(char c) { switch(c) { case 'r': r = true; break; case 'g': g = true; break; case 'b': b = true; break; case 'y': y = true; break; } } void reset() { r= g= b= y = false; } }; class Hr { public: int x, y; K klice; inline int toint() { return x + MAX*y + MAX*MAX*klice.toint(); } void fromint(int a) { klice.fromint(a / (MAX*MAX)); a %= MAX*MAX; x = a%MAX; y = a/MAX; } void push(deque &p) { if (pozice[x][y].stena) return; if (pozice[x][y].dvere && !klice.ma(pozice[x][y].dvere)) return; if (pozice[x][y].klic) { klice.dej(pozice[x][y].klic); } int c = toint(); if (!used[c]) { p.push_back(c); used[c] = true; } } bool isfinal() { return pozice[x][y].exit; } void reset() { klice.reset(); x = -1; y = -1;} }; Hr hrac; void read() { string s; getline(cin, s); for (int i = 0; i < H; i++) { getline(cin, s); for (int j = 0; j < W; j++) { pozice[j][i].load(s[j]); if (s[j] == '*') { hrac.x = j; hrac.y = i; } } } } int solve() { deque pos; int len = 0; pos.push_back(hrac.toint()); pos.push_back(-1); Hr h, hn; while (pos.size() > 1) { int p = pos.front(); pos.pop_front(); if (p == -1) { len++; pos.push_back(-1); continue; } h.fromint(p); if ( h.isfinal() ) return len; if (h.x > 0) { hn = h; hn.x--; hn.push(pos); } if (h.x < W-1) { hn = h; hn.x++; hn.push(pos);} if (h.y > 0) { hn = h; hn.y--; hn.push(pos);} if (h.y < H-1) { hn = h; hn.y++; hn.push(pos);} } return -1; } int main() { cin >> H; cin >> W; while (W + H > 0) { nul(); hrac.reset(); read(); int x = solve(); if (x < 0) cout << "The poor student is trapped!" << endl; else cout << "Escape possible in " << x << " steps." << endl; cin >> H; cin >> W; } return 0; }