您的位置:首页 > 其它

hdu 1429 胜利大逃亡(续)(BFS+状压)

2015-11-10 20:09 381 查看
题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1429

思路:

先想到用BFS 求得最短的时间。然后看到要拿不同的钥匙开门,总共最多有10把钥匙,最多为2^10,所以考虑状压。

代码:

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int n,m,t,si,sj,ei,ej;
char s[24][24];
int vis[24][24][3030],maze[24][24],dir[4][2]={0,1,0,-1,1,0,-1,0};
struct node{
int x,y,step,state;
};
queue<node>qu;
int bfs()
{
while(!qu.empty())qu.pop();
node now,next;
now.x=si;
now.y=sj;
now.step=0;
now.state=0;
qu.push(now);
while(!qu.empty())
{
now=qu.front();
qu.pop();
if(now.x==ei&&now.y==ej){
return now.step;}
for(int i=0;i<4;i++)
{
next=now;
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
next.step=now.step+1;
if(next.x<=0||next.y<=0||next.x>n||next.y>m)continue;
if(maze[next.x][next.y]==-1)continue;
if(maze[next.x][next.y]>0){
if((now.state&maze[next.x][next.y])>0){   //对于某一扇门,可以看当前状态是否已经有了对应钥匙。
next.state=now.state;
if(!vis[next.x][next.y][next.state])
{vis[next.x][next.y][next.state]=1;
qu.push(next);
}
}
if((now.state&maze[next.x][next.y])==0&&s[next.x][next.y]>='a'&&s[next.x][next.y]<='z'){    //如果是钥匙并且没有拿过,就拿过来。
next.state=now.state|maze[next.x][next.y];
if(!vis[next.x][next.y][next.state])
{vis[next.x][next.y][next.state]=1;
qu.push(next);
}
}
}
if(maze[next.x][next.y]==0&&!vis[next.x][next.y][next.state]){
vis[next.x][next.y][next.state]=1;
qu.push(next);
}
}
}
return -1;
}
int main()
{
int i,j,k;
while(scanf("%d%d%d",&n,&m,&t)!=EOF)
{
memset(vis,0,sizeof(vis));
memset(maze,0,sizeof(maze));
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
cin>>s[i][j];
if(s[i][j]=='@'){
si=i;sj=j;
maze[i][j]=0;
}
if(s[i][j]=='^'){
ei=i;ej=j;
maze[i][j]=0;
}
if(s[i][j]=='.'){
maze[i][j]=0;
}
if(s[i][j]=='*'){
maze[i][j]=-1;
}
if(s[i][j]>='a'&&s[i][j]<='z'){
maze[i][j]=1<<(s[i][j]-'a');
}
if(s[i][j]>='A'&&s[i][j]<='Z'){
maze[i][j]=1<<(s[i][j]-'A');
}
}
int ans= bfs();
if(ans>=t)printf("-1\n");
else printf("%d\n",ans);
}
}
/*
3 3 5
@a*
*aa
^AA

2 3 4
@a^
A*.

3 3 10
@a*
*bA
^Cc
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: