#include #include #include using std::pair; using std::make_pair; #define MP make_pair #define X first #define Y second #define REP(a, b) for(int a=0; a<(b); a++) int tab[100][100][1<<4]; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; char buf[100]; char plansza[100][120]; pair, int> Q[10000*16]; int isKey(char c) { return c=='b' || c=='y' || c=='r' || c=='g'; } int getKey(char c) { if (c=='b') return 1; if (c=='r') return 2; if (c=='g') return 4; return 8; } bool moznaOtworzyc(int maska, char c) { if (c=='#') return false; if (isKey(c+'a'-'A')) return (maska&getKey(c+'a'-'A'))!=0; return true; } int main() { while(true) { fgets(buf, 100, stdin); int r, c; sscanf(buf, "%d%d", &r, &c); if (r==0 && c==0) break; REP(i, r) fgets(plansza[i], 120, stdin); int x, y; REP(xx, r) REP(yy, c) if(plansza[xx][yy]=='*') { x = xx; y = yy; goto next; } next: memset(tab, -1, sizeof(tab)); tab[x][y][0] = 0; int st = 0, en = 1; Q[0] = MP(MP(x, y), 0); int ret = -1; while(st pos = Q[st].X; int keys = Q[st++].Y; int val = tab[pos.X][pos.Y][keys]; if (isKey(plansza[pos.X][pos.Y])) { keys |= getKey(plansza[pos.X][pos.Y]); } REP(d, 4) { if (pos.X+dx[d]>=0 && pos.X+dx[d]=0 && pos.Y+dy[d]