有一个迷宫还有四种钥匙,对应四种门,问走出迷宫的最少步数。
二进制状态压缩step[s][x][y]表示走到点x,y,获得钥匙的状态为s的最少步数。
类似于这道题:http://acm.hdu.edu.cn/showproblem.php?pid=1429
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct Node
{
int s,x,y;
Node(){}
Node(int a,int b,int c)
{s = a; x = b; y = c;}
};
Node st;
char mp[110][110];
int step[1<<4][101][101],n,m,lv[300];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
bool inarea(int i,int j)
{
if(i < 1||i > n||j < 1||j > m) return false;
else return true;
}
bool opn(int i,int j,int S)
{
if(mp[i][j] == 'B'||mp[i][j] == 'Y'||mp[i][j] == 'R'||mp[i][j] == 'G')
{
if((1<<lv[mp[i][j]])&S) return true;
else return false;
}
else return true;
}
void init()
{
memset(mp,0,sizeof mp);
memset(step,-1,sizeof step);
}
void bfs()
{
queue<Node> Q;
Q.push(st);
step[0][st.x][st.y] = 0;
while(!Q.empty())
{
Node u = Q.front();
Q.pop();
if(mp[u.x][u.y] == 'X')
{
printf("Escape possible in %d steps.\n",step[u.s][u.x][u.y]);
return;
}
for(int i = 0; i < 4; i++)
{
int tx = u.x+dir[i][0],ty = u.y+dir[i][1],S = u.s;
if(!inarea(tx,ty)||!opn(tx,ty,S)||mp[tx][ty] == '#'||step[S][tx][ty] != -1) continue;
if(mp[tx][ty] == 'b'||mp[tx][ty] == 'y'||mp[tx][ty] == 'r'||mp[tx][ty] == 'g')
S = ((1<<lv[mp[tx][ty]])|S);
step[S][tx][ty] = step[u.s][u.x][u.y]+1;
Q.push(Node(S,tx,ty));
}
}
printf("The poor student is trapped!\n");
}
int main()
{
lv['B'] = 0,lv['Y'] = 1,lv['R'] = 2,lv['G'] = 3;
lv['b'] = 0,lv['y'] = 1,lv['r'] = 2,lv['g'] = 3;
while(scanf("%d%d",&n,&m) != EOF&&n+m)
{
init();
for(int i = 1; i <= n; i++)
scanf("%s",mp[i]+1);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(mp[i][j] == '*')
{
st.s = 0,st.x = i,st.y = j;
break;
}
bfs();
}
}