#include #include #include using namespace std; struct stanje { int x, y; int key; int d; stanje(int X, int Y, int KEY,int D) { x = X; y = Y; key = KEY; d=D; } }; int dx[] = {0, 0, -1, 1}; int dy[] = {-1,1, 0, 0}; int R,C; bool visited[100][100][16]; char matrica[100][100]; int bfs( stanje poc) { queue< stanje > Q; Q.push(poc); while ( !Q.empty() ) { stanje tren = Q.front(); Q.pop(); visited[tren.x][tren.y][tren.key] =true; for (int k = 0; k < 4; ++k) { int nx = tren.x + dx[k]; int ny = tren.y + dy[k]; if ( nx < 0 || ny < 0 || nx>R || ny >C || matrica[nx][ny] =='#' || visited[nx][ny][tren.key]) continue; if ( matrica[nx][ny] =='.' || (matrica[nx][ny]=='B' && tren.key&1) || (matrica[nx][ny]=='Y' && tren.key&(1<<1)) || (matrica[nx][ny]=='R' && tren.key&(1<<2)) || (matrica[nx][ny]=='G' && tren.key&(1<<3))) { Q.push(stanje(nx,ny,tren.key,tren.d+1)); } else if(matrica[nx][ny]=='b') { Q.push(stanje(nx,ny,tren.key|1,tren.d+1)); } else if(matrica[nx][ny]=='y') { Q.push(stanje(nx,ny,tren.key|(1<<1),tren.d+1)); } else if(matrica[nx][ny]=='r') { Q.push(stanje(nx,ny,tren.key|(1<<2),tren.d+1)); } else if(matrica[nx][ny]=='g') { Q.push(stanje(nx,ny,tren.key|(1<<3),tren.d+1)); } else if(matrica[nx][ny]=='X') return tren.d+1; } } return -1; } int main(void) { while(1) { scanf("%d%d",&R,&C); if(R+C==0) return 0; for(int i=0;i