/*
类型:状态搜索
解析:10把钥匙,2^10种状态,每一个点都有1024种状态,搜索过得状态就不能再次搜索,
符合结果的状态很多,用BFS搜索最优状态。。。
*/
#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<queue>
using namespace std;
int s[25][25][1028]; / 标记每个点的状态
struct node{
int x,y,time,key;
};
int dir[4][2]={ {1,0},{-1,0},{0,1},{0,-1} };
int n,m,t,ex,ey,sx,sy;
char mp[25][25];
queue<node>que;
void bfs(int x,int y){
node te;
te.x=x; te.y=y; te.time=0; te.key=0;
que.push(te);
s[x][y][te.key]=1;
while(!que.empty()){
te=que.front();
que.pop();
if(te.x==ex && te.y==ey && te.time<t){
printf("%d\n",te.time);
return ;
}
for(int i=0;i<4;i++){
node p;
p.x=te.x+dir[i][0];
p.y=te.y+dir[i][1];
p.time=te.time+1;
p.key = te.key;
if(p.x<=0 || p.x>n || p.y<=0 || p.y>m || s[p.x][p.y][p.key] || mp[p.x][p.y]=='*') continue;
if(mp[p.x][p.y]=='.'){
s[p.x][p.y][p.key]=1;/标记当前这个点的状态已经搜索过了,下次不可以再搜索。。
que.push(p);
continue;
}
if(mp[p.x][p.y]>='a' && mp[p.x][p.y]<='j'){拿到了钥匙
int key=1<<(mp[p.x][p.y]-'a');
p.key=p.key|key;
s[p.x][p.y][p.key]=1;
que.push(p);
}
if(mp[p.x][p.y]>='A' && mp[p.x][p.y]<='J'){开锁
int key=(mp[p.x][p.y]-'A');
if(((p.key>>key)&1)==0) continue; 没有钥匙
s[p.x][p.y][p.key]=1;
que.push(p);
}
}
}
printf("-1\n");
}
int main(){
while(cin>>n>>m>>t){
while(!que.empty()) que.pop();
for(int i=1;i<=n;i++){
cin>>mp[i]+1;
for(int j=1;j<=m;j++){
if(mp[i][j]=='@'){
sx=i,sy=j;
mp[i][j]='.';
}
if(mp[i][j]=='^'){
ey=j,ex=i;
mp[i][j]='.';
}
}
}
memset(s,0,sizeof(s));
bfs(sx,sy);
}
}
/*
4 5 17
@A.B.
a*.*.
*..*^
c..b*
4 5 16
@A.B.
a*.*.
*..*^
c..b*
*/
HDU 1429 BFS+状态搜索
最新推荐文章于 2020-08-28 22:24:59 发布