首页 > 代码库 > hdu 1429 状压bfs

hdu 1429 状压bfs


#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#define inf 0x3f3f3f3f
#define ll __int64
#define mod 1000000007
using namespace std;

struct node
{
    int x,y,key,cnt;
}now,tmp;

int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
int n,m,t,sx,sy,ex,ey,vis[25][25][1<<11];
char mp[25][25];

bool ok(int x,int y,int key)
{
    if(x<0||x>=n||y<0||y>=m||vis[x][y][key]||mp[x][y]=='*') return 0;
    return 1;
}

int bfs()
{
    queue<node> q;
    now.x=sx;
    now.y=sy;
    now.cnt=0;
    now.key=0;
    vis[sx][sy][0]=1;//@#$%^&**!!
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            tmp.x=now.x+dx[i];
            tmp.y=now.y+dy[i];
            tmp.cnt=now.cnt+1;
            tmp.key=now.key;
            if(tmp.x==ex&&tmp.y==ey) return tmp.cnt;
            if(mp[tmp.x][tmp.y]>='a'&&mp[tmp.x][tmp.y]<='j')
            {
                tmp.key|=(1<<(mp[tmp.x][tmp.y]-'a'));
            }
            else if(mp[tmp.x][tmp.y]>='A'&&mp[tmp.x][tmp.y]<='J')
            {
                if((tmp.key&(1<<(mp[tmp.x][tmp.y]-'A')))==0)
                    continue;
            }
            if(!ok(tmp.x,tmp.y,tmp.key)) continue;
            vis[tmp.x][tmp.y][tmp.key]=1;
            q.push(tmp);
        }
    }
    return -1;
}

int main()
{
    int i,j,ans;
    while(~scanf("%d%d%d",&n,&m,&t))
    {
        for(i=0;i<n;i++)
        {
            scanf("%s",mp[i]);
            for(j=0;j<m;j++)
            {
                if(mp[i][j]=='@')
                {
                    sx=i;
                    sy=j;
                }
                if(mp[i][j]=='^')
                {
                    ex=i;
                    ey=j;
                }
            }
        }
        memset(vis,0,sizeof vis);
        ans=bfs();
        if(ans<t) printf("%d\n",ans);
        else printf("-1\n");
    }
    return 0;
}