HDU 1429 BFS+状态压缩

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <queue>
using namespace std;
const int N=21;
const int KEY=10;
char s[N][N];
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
int n,m,k;
bool hash[N][N][1<<KEY];//一定要注意范围,不然就会一直错


struct node {
    int x,y,step,key;
};


int kk(char c) {
    return c-(isupper(c)?'A':'a');
}


int bfs(int x,int y) {
    int i;
    queue<node>q;
    node cur,next;
    cur.x=x;
    cur.y=y;
    cur.step=0;
    cur.key=0;
    hash[cur.x][cur.y][cur.key]=1;
    q.push(cur);
    while(!q.empty()) {
        cur=q.front();
        q.pop();
        if(cur.step>=k)break;
        for(i=0; i<4; i++) {
            next.x=cur.x+dir[i][0];
            next.y=cur.y+dir[i][1];
            next.key=cur.key;
            next.step=cur.step+1;
            if(next.x<0||next.x>=n||next.y<0||next.y>=m||s[next.x][next.y]=='*')continue;
             next.key=cur.key;
            next.step=cur.step+1;
            if(isupper(s[next.x][next.y])&&!(next.key&(1<<kk(s[next.x][next.y]))))continue;
            if(islower(s[next.x][next.y])) next.key=next.key|(1<<kk(s[next.x][next.y]));
            if(s[next.x][next.y]=='^')return next.step;
            if(!hash[next.x][next.y][next.key]) {
                hash[next.x][next.y][next.key]=1;
                q.push(next);
            }
        }
    }
    return -1;
}


int main() {
    int flag1,flag2;
    while(scanf("%d%d%d",&n,&m,&k)!=EOF) {
        k-=1;
        int flag3=0;
        for(int i=0; i<n; i++)
            scanf("%s",&s[i]);
        for(int i=0; i<n; i++) {
            for(int j=0; j<m; j++) {
                if(s[i][j]=='@') {
                    flag1=i;
                    flag2=j;
                    flag3=1;
                    break;
                }
            }
            if(flag3)break;
        }
        int num;
        memset(hash,0,sizeof(hash));
        num=bfs(flag1,flag2);
        printf("%d\n",num);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值