HDU1885 Key Task(BFS)

有一个迷宫还有四种钥匙,对应四种门,问走出迷宫的最少步数。
二进制状态压缩step[s][x][y]表示走到点x,y,获得钥匙的状态为s的最少步数。
类似于这道题:http://acm.hdu.edu.cn/showproblem.php?pid=1429

#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct Node
{
    int s,x,y;
    Node(){}
    Node(int a,int b,int c)
    {s = a; x = b; y = c;}
};
Node st;
char mp[110][110];
int step[1<<4][101][101],n,m,lv[300];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
bool inarea(int i,int j)
{
    if(i < 1||i > n||j < 1||j > m) return false;
    else return true;
}
bool opn(int i,int j,int S)
{
    if(mp[i][j] == 'B'||mp[i][j] == 'Y'||mp[i][j] == 'R'||mp[i][j] == 'G')
    {
        if((1<<lv[mp[i][j]])&S) return true;
        else return false;
    }
    else return true;
}
void init()
{
    memset(mp,0,sizeof mp);
    memset(step,-1,sizeof step);
}
void bfs()
{
    queue<Node> Q;
    Q.push(st);
    step[0][st.x][st.y] = 0;
    while(!Q.empty())
    {
        Node u = Q.front();
        Q.pop();
        if(mp[u.x][u.y] == 'X')
        {
            printf("Escape possible in %d steps.\n",step[u.s][u.x][u.y]);
            return;
        }

        for(int i = 0; i < 4; i++)
        {
            int tx = u.x+dir[i][0],ty = u.y+dir[i][1],S = u.s;
            if(!inarea(tx,ty)||!opn(tx,ty,S)||mp[tx][ty] == '#'||step[S][tx][ty] != -1) continue;
            if(mp[tx][ty] == 'b'||mp[tx][ty] == 'y'||mp[tx][ty] == 'r'||mp[tx][ty] == 'g')
                S = ((1<<lv[mp[tx][ty]])|S);
            step[S][tx][ty] = step[u.s][u.x][u.y]+1;
            Q.push(Node(S,tx,ty));
        }
    }
    printf("The poor student is trapped!\n");
}
int main()
{
    lv['B'] = 0,lv['Y'] = 1,lv['R'] = 2,lv['G'] = 3;
    lv['b'] = 0,lv['y'] = 1,lv['r'] = 2,lv['g'] = 3;
    while(scanf("%d%d",&n,&m) != EOF&&n+m)
    {
        init();
        for(int i = 1; i <= n; i++)
            scanf("%s",mp[i]+1);
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
                if(mp[i][j] == '*')
                {
                    st.s = 0,st.x = i,st.y = j;
                    break;
                }
        bfs();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值