题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1885
Key Task
题目大意:*代表起点,X代表终点,B,Y,R,G分别代表四个门,b,y,r,g分别代表四把钥匙,只有拿了钥匙,才能开相应的门。问你最后能否达到终点,能输出最小步数,不能输出“The poor student is trapped!”。
解题思路:对于四把钥匙,可以使用状态压缩,开个三维数组做下标记,然后就用平常的bfs求解即可!!!
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<cctype>
#include<algorithm>
#define INF 0xfffffff
using namespace std;
struct node
{
int x,y,step;
int key;
};
int r,c;
char maze[110][110];
int vis[110][110][30];
int dx[]={-1,0,1,0},dy[]={0,-1,0,1};
char door[]={'B','Y','R','G'};
char key[]={'b','y','r','g'};
int minn;
void bfs(int x,int y)
{
int i,j,k;
queue<node> Q;
node p,q;
p.key=p.step=0;
p.x=x;p.y=y;
vis[x][y][p.key]=1;
Q.push(p);
while(!Q.empty())
{
p=Q.front();
Q.pop();
if(maze[p.x][p.y]=='X')
minn=min(minn,p.step);
for(i=0;i<4;i++)
{
q.x=p.x+dx[i];
q.y=p.y+dy[i];
q.step=p.step+1;
q.key=p.key;
if(q.x<0||q.x>=r||q.y<0||q.y>=c||maze[q.x][q.y]=='#')
continue;
if(isupper(maze[q.x][q.y])&&maze[q.x][q.y]!='X')
{
for(j=0;j<4;j++)
{
if(maze[q.x][q.y]==door[j])
{
if(q.key&(1<<j))
{
if(!vis[q.x][q.y][q.key])
{
vis[q.x][q.y][q.key]=1;
Q.push(q);
}
break;
}
}
}
}
else if(islower(maze[q.x][q.y]))
{
for(j=0;j<4;j++)
{
if(maze[q.x][q.y]==key[j])
{
if((q.key&(1<<j))==0)
q.key+=(1<<j);
if(!vis[q.x][q.y][q.key])
{
vis[q.x][q.y][q.key]=1;
Q.push(q);
}
}
}
}
else
{
if(!vis[q.x][q.y][q.key])
{
vis[q.x][q.y][q.key]=1;
Q.push(q);
}
}
}
}
}
int main()
{
while(scanf("%d%d",&r,&c),r+c)
{
int i,j,ans=0;
minn=INF;
for(i=0;i<r;i++)
scanf("%s",maze[i]);
memset(vis,0,sizeof(vis));
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
if(maze[i][j]=='*')
{
bfs(i,j);
break;
}
}
if(minn==INF)
printf("The poor student is trapped!\n");
else
printf("Escape possible in %d steps.\n",minn);
}
return 0;
}