您的位置:首页 > 其它

hash+状态压缩+uva10944

2014-06-30 15:56 357 查看
思路:用二进制表示当前果子被摘去的情况,进行BFS,hash表示这种状态是否出现过

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=25;
bool hash[maxn][maxn][32768];
int grid[maxn][maxn];
int n,m,s,e,sum;
char tmp[maxn];
struct node
{
    int x,y;
    int t,cnt;
};
int dx[]={-1,-1,-1,0,0,1,1,1};
int dy[]={-1,0,1,-1,1,-1,0,1};
int  solve()
{
    int ans=0;
    memset(hash,0,sizeof(hash));
    hash[s][e][0]=1;
    queue<node> q;
    node a;
    a.x=s,a.y=e,a.t=0,a.cnt=0;
    q.push(a);
    while(!q.empty())
    {
        node b=q.front();
        q.pop();
        if(b.x==s&&b.y==e&&b.t==sum-1){return b.cnt;}
        for(int i=0;i<8;i++)
        {
            a.x=b.x+dx[i];
            a.y=b.y+dy[i];
            int val=grid[a.x][a.y];
            if(a.x>=1&&a.x<=n&&a.y>=1&&a.y<=m&&!hash[a.x][a.y][b.t|val])
            {
                a.t=b.t|val;
                a.cnt=b.cnt+1;
                q.push(a);
                hash[a.x][a.y][b.t|val]=1;

            }
        }
        //ans++;
    }
}
int main()
{
    freopen("in.txt","r",stdin);
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        sum=1;
        memset(grid,0,sizeof(grid));

        for(int i=1;i<=n;i++)
        {
            scanf("%s",tmp+1);
            for(int j=1;j<=m;j++)
            {
                if(tmp[j]=='L'){s=i,e=j;}
                else if(tmp[j]=='#'){grid[i][j]=sum;sum<<=1;}
            }
        }
        cout<<solve()<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: