POJ 1324 状压搜索(4进制)

本文介绍了一种使用4进制压缩存储蛇身位置的方法,并通过广度优先搜索(BFS)来解决蛇从头部到(1,1)点的最短路径问题。文章详细展示了如何进行位运算特判及实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给出图中蛇的范围和不可到达的地方,求蛇头到(1,1)点的最少代价

用4进制压缩存蛇身体相对蛇头的位置,BFS即可

特判蛇头在(1,1) 时的情况

注意位运算


#include "stdio.h"
#include "string.h"
#include "queue"
using namespace std;

int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};


struct node
{
    int x,y,step,status;
}cur,next;;
int n,m,l;
int map[21][21];
int hash[21][21][1<<14];
int judge(int x,int y,node a)
{
    int i;
    int ass[10];
    for (i=l-1;i>=1;i--)
    {
        ass[i]=a.status&3;
        a.status>>=2;
    }
    for (i=1;i<l;i++)
    {
        a.x+=dir[ass[i]][0];
        a.y+=dir[ass[i]][1];
        if (a.x==x && a.y==y) return 1;
    }
    return 0;
}
int find_dir(int x1,int y1,int x2,int y2)
{
    if (x1-1==x2) return 0;
    if (x1+1==x2) return 2;
    if (y1-1==y2) return 3;
    if (y1+1==y2) return 1;

}
int bfs()
{
    queue<node>q;
    int lx,ly,f,k,x,y,i;
    scanf("%d%d",&cur.x,&cur.y);
    lx=cur.x;
    ly=cur.y;
    cur.step=cur.status=0;
    for (i=2;i<=l;i++)
    {
        scanf("%d%d",&x,&y);
        if (x==lx-1) f=0;
        if (x==lx+1) f=2;
        if (y==ly-1) f=3;
        if (y==ly+1) f=1;
        lx=x; ly=y;
        cur.status=(cur.status<<2)+f;
    }
    hash[cur.x][cur.y][cur.status]=1;
    scanf("%d",&k);
    while(k--)
    {
        scanf("%d%d",&x,&y);
        map[x][y]=1;
    }
    if(cur.x==1 && cur.y==1) return 0;
    q.push(cur);

    while(!q.empty())
    {
        cur=q.front();
        q.pop();
        for (i=0;i<4;i++)
        {
            next.x=cur.x+dir[i][0];
            next.y=cur.y+dir[i][1];
            if (next.x<1 || next.x>n || next.y<1 || next.y>m) continue;
            if (map[next.x][next.y]==1) continue;
            if (judge(next.x,next.y,cur)==1) continue;
            next.step=cur.step+1;
            next.status=(cur.status>>2);
            x=find_dir(next.x,next.y,cur.x,cur.y);
            next.status+=(x<<(2*l-4));
            if (hash[next.x][next.y][next.status]==1) continue;
            hash[next.x][next.y][next.status]=1;
            if (next.x==1 && next.y==1)return next.step;
            q.push(next);

        }
    }
    return -1;

}
int main()
{
    int Case;
    Case=0;
    while (scanf("%d%d%d",&n,&m,&l)!=EOF)
    {
        if (n+m+l==0) break;
        memset(hash,0,sizeof(hash));
        memset(map,0,sizeof(map));
        printf("Case %d: %d\n",++Case,bfs());

    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值