hdu1429 bfs+状态压缩

题目是十把钥匙,所以可以用状态压缩来表示(不解释),之后就是简单的BFS了,不过貌似有点容易爆内存的样子啊….

#include <iostream>
#include <cmath>
#include <cctype>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <utility>
#define inf (1<<28)
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mid ((l+r)>>1)
using namespace std;
#define maxn 24

struct Node
{
     int x, y, t, state;
};
char g[maxn][maxn];
int v[maxn][maxn][1<<10];
int n,m,T;
queue<Node>q;
int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
inline int  ok(char c)
{
     return c - (isupper(c) ? 'A' : 'a');
}
inline int check(int x, int y)
{
     return (x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '*');
}
int Bfs(int x,int y,int t,int state)
{
    Node a,b;
    while(!q.empty())q.pop();
    a.x=x,a.y=y,a.t=t,a.state=state;
    q.push(a);
    v[x][y][state]=1;
    memset(v,0,sizeof(v));
    while(!q.empty())
    {
        a=q.front();
        q.pop();
        if(a.t>=T)break;
        for(int i=0;i<4;i++)
        {
            b.x=a.x+dir[i][0];
            b.y=a.y+dir[i][1];
            b.state=a.state;
            b.t=a.t+1;
            if(check(b.x,b.y)||v[b.x][b.y][b.state])continue;//越界,已访问
            if(isupper(g[b.x][b.y])&&!(b.state&(1<<ok(g[b.x][b.y]))))continue;//没钥匙
            if(islower(g[b.x][b.y]))b.state|=1<<ok(g[b.x][b.y]);//状态压缩
            if(g[b.x][b.y]=='^')return b.t;
            if(!v[b.x][b.y][b.state]){
                v[b.x][b.y][b.state]=1;
                q.push(b);
            }
        }
    }
    return -1;
}
int main()
{
     int x=0,y=0;
     while(~scanf("%d%d%d",&n,&m,&T)){
          T -= 1;
          for(int i=0;i<n;i++){
               scanf("%s", g[i]);
               for(int j=0;j<m;j++){
                    if(g[i][j]=='@'){
                         g[i][j]='.';
                         x=i,y=j;
                    }
               }
          }
          printf("%d\n", Bfs(x,y,0,0));
     }
     return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值