—题目:http://acm.hit.edu.cn/hoj/problem/view?id=2706
题目描述:可怜的大学生被困在迷宫里了,迷宫里有 B 、 Y 、 G 、 R 四种门,也有 b 、 y 、 g 、 r 四种钥匙,对应的钥匙可以打开对应的门。迷宫有多个出口。问,如果大学生每步可以上下左右移动。那么他最少用多少不可以从迷宫中解脱,或者一辈子被困在迷宫中。
分析:一共有四把钥匙,所以还需加一维数组来保存状态。
题目描述:可怜的大学生被困在迷宫里了,迷宫里有 B 、 Y 、 G 、 R 四种门,也有 b 、 y 、 g 、 r 四种钥匙,对应的钥匙可以打开对应的门。迷宫有多个出口。问,如果大学生每步可以上下左右移动。那么他最少用多少不可以从迷宫中解脱,或者一辈子被困在迷宫中。
#include <iostream>
#include <algorithm>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
using namespace std;
const int N=111;
typedef struct point
{
int x,y,key,step;
}point;
bool vis[N][N][16];
char c[N][N];
int n,m,x,y;
int d[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int main()
{
//freopen("f.txt","r",stdin);
queue<point>q;
while(scanf("%d%d",&n,&m)&&(n+m)){
for(int i=1;i<=n;i++){
getchar();
for(int j=1;j<=m;j++){
scanf("%c",&c[i][j]);
if(c[i][j]=='*')x=i,y=j;
}
}
// for(int i=1;i<=n;i++){
// for(int j=1;j<=m;j++)
// printf("%c",c[i][j]);
// printf("\n");
// }
while(!q.empty())q.pop();
memset(vis,0,sizeof(vis));
point p,t;
int ans=0;
p.key=0,p.step=0,p.x=x,p.y=y;
q.push(p);
vis[x][y][0]=1;
bool flag=false;
while(!q.empty()){
t=q.front();
q.pop();
if(flag)break;
for(int i=0;i<4;i++){
int xx=d[i][0]+t.x;
int yy=d[i][1]+t.y;
if(xx>0&&xx<=n&&yy>0&&yy<=m&&!vis[xx][yy][t.key]&&c[xx][yy]!='#'){
p.step=t.step+1;
p.x=xx;
p.y=yy;
p.key=t.key;
// vis[xx][yy][t.key]=1;
if(c[xx][yy]=='.'||c[xx][yy]=='*'){
q.push(p);
vis[xx][yy][p.key]=1;
}
else if(c[xx][yy]=='X'){
ans=p.step;
flag=1;
break;
}
else if(c[xx][yy]=='b'){
if(!((t.key>>3)&1))
p.key=t.key+8;
q.push(p);
vis[xx][yy][t.key]=1;
vis[xx][yy][p.key]=1;
// cout<<'b'<<endl;
}
else if(c[xx][yy]=='y'){
if(!((t.key>>2)&1))
p.key=t.key+4;
q.push(p);
vis[xx][yy][t.key]=1;
vis[xx][yy][p.key]=1;
// cout<<'y'<<endl;
}
else if(c[xx][yy]=='r'){
if(!((t.key>>1)&1))
p.key=t.key+2;
q.push(p);
vis[xx][yy][t.key]=1;
vis[xx][yy][p.key]=1;
// cout<<'r'<<endl;
}
else if(c[xx][yy]=='g'){
if(!(t.key&1))
p.key=t.key+1;
q.push(p);
vis[xx][yy][t.key]=1;
vis[xx][yy][p.key]=1;
// cout<<'g'<<endl;
}
else if(c[xx][yy]=='B'&&((t.key>>3)&1)){
vis[xx][yy][t.key]=1;
// cout<<'B'<<endl;
q.push(p);
}
else if(c[xx][yy]=='Y'&&((t.key>>2)&1)){
vis[xx][yy][t.key]=1;
// cout<<'Y'<<endl;
q.push(p);
}
else if(c[xx][yy]=='R'&&((t.key>>1)&1)){
vis[xx][yy][t.key]=1;
// cout<<'R'<<endl;
q.push(p);
}
else if(c[xx][yy]=='G'&&(t.key&1)){
vis[xx][yy][t.key]=1;
// cout<<'G'<<endl;
q.push(p);
}
}
}
}
if(flag)printf("Escape possible in %d steps.\n",ans);
else printf("The poor student is trapped!\n");
}
return 0;
}