HDU 1429 BFS+状态搜索

/*

类型:状态搜索
解析: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*

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值