题意:
走迷宫,问走出迷宫最少需要多少步,其中要想通过一个含有门的格子,需要先经过含有该门对应的钥匙的地方
题解:
之前做过类似的一道题目,十分相似,不过这次做的时候还是出了点小问题,我vis只开了两位,发现就无法走回头路了,后来多加了一位存钥匙的状态,这样就可以判断重复情况了,以后记住了
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=105;
int n,m,sx,sy,ex,ey;
char g[N][N];
bool vis[N][N][16];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
int x,y,key,step;
};
int judged(char ch)
{
if(ch=='B')return 1<<0;
if(ch=='Y')return 1<<1;
if(ch=='R')return 1<<2;
if(ch=='G')return 1<<3;
}
int judgek(char ch)
{
if(ch=='b')return 1<<0;
if(ch=='y')return 1<<1;
if(ch=='r')return 1<<2;
if(ch=='g')return 1<<3;
return 0;
}
void solve()
{
memset(vis,0,sizeof(vis));
queue<node>q;
node u,v;
u.x=sx;u.y=sy;u.key=0;u.step=0;vis[u.x][u.y][u.key]=1;
q.push(u);
while(!q.empty()){
u=q.front();q.pop();
if(g[u.x][u.y]=='X'){printf("Escape possible in %d steps.\n",u.step);return;}
for(int i=0;i<4;i++){
v.x=u.x+dir[i][0];v.y=u.y+dir[i][1];v.step=u.step+1;v.key=u.key|judgek(g[v.x][v.y]);
if(v.x<1||v.x>n)continue;
if(v.y<1||v.y>m)continue;
if(g[v.x][v.y]=='#')continue;
if(vis[v.x][v.y][v.key])continue;
if(g[v.x][v.y]=='B'||g[v.x][v.y]=='Y'||g[v.x][v.y]=='R'||g[v.x][v.y]=='G'){
if(!(u.key&judged(g[v.x][v.y]))) continue;
}
vis[v.x][v.y][v.key]=1;
q.push(v);
}
}
printf("The poor student is trapped!\n");
}
int main()
{//freopen("C:\\Users\\Administrator\\Desktop\\input.txt","r",stdin);
//B Y R G door
//# wall
//. free square
//* my position
//b y r g key
//X exit
while(scanf("%d%d",&n,&m)&&n+m){
for(int i=1;i<=n;i++)scanf("%s",g[i]+1);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(g[i][j]=='*'){sx=i;sy=j;g[sx][sy]='.';break;break;}
}
}
solve();
}
return 0;
}