BFS练习

BFS练习

概述

POJ1324

该题在BFS的基础上加入了状态压缩;
由于蛇不能碰到自己的身体,因此每一步状态需要记录身体的位置;如果直接使用int记录身体每一段坐标(x, y),内存消耗将非常大;
考虑这么一种压缩:移动过程中蛇身体的每一段的下一步位置是其前一段的当前位置,因此可以从蛇头位置往后回推蛇身的位置;另外,BFS的过程中是一定会记录移动方向的,记录身体的每一段的移动方向,由当前某一段身体位置往其反方向移动就可得到移动前其后一段的位置,因此可考虑记录身体每一段的下一步移动方向的反方向,这么做将状态压缩到了4*L个,同时状态压缩的按位移动操作效率远高于用int记录位置时对位置的修改

AC Code

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;

struct xx {
    int x, y;
} body[10];

struct node {
    int x, y;
    int body_move;
    int step;
};

int stone[25][25];
int vis[25][25][1<<14];
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
int reverse_move[4] = {1, 0, 3, 2};
int n, m, L;
int del;

bool check_body(node p, int _x, int _y)
{   
    int x = p.x, y = p.y;
    for(int i=2; i<=L; ++i) {
        int t = 0;
        if(p.body_move&1) t += 1;
        p.body_move >>= 1;
        if(p.body_move&1) t += 2;
        p.body_move >>= 1;
        x += dx[t];
        y += dy[t];
        if(_x == x && _y == y) 
            return false;
    }
    return true;
}


int bfs(node st)
{
    memset(vis, 0, sizeof(vis));
    queue<node> que;
    que.push(st);
    while(!que.empty()) {
        node p = que.front(); que.pop();
        if(p.x == 1 && p.y == 1){
            return p.step;
        }
        node _p;
        for(int i=0; i<4; ++i) {
            int x = p.x + dx[i];
            int y = p.y + dy[i];
            if(x<=0 || y<=0 || x>m || y>n || stone[x][y] ||!check_body(p, x, y)) continue;
            _p.x = x;
            _p.y = y;
            _p.body_move = ((p.body_move<<2)&del) | reverse_move[i];
            if(vis[y][x][_p.body_move]) continue;
            vis[y][x][_p.body_move] = 1;
            _p.step = p.step + 1;
            que.push(_p);
        }
    }
    return -1;
}


int main()
{
    int K, x, y, cas=0;
    while(scanf("%d%d%d", &n, &m, &L)){
        if(n==0 && m==0 && L==0) break;
        for(int i=1; i<=L; ++i) scanf("%d%d", &body[i].y, &body[i].x);
        scanf("%d", &K);
        memset(stone, 0, sizeof(stone));
        for(int i=1; i<=K; ++i) {
            scanf("%d%d", &y, &x);
            stone[x][y] = 1;
        }
        del = (1<<((L-1)*2))-1;
        node st;
        st.x = body[1].x; st.y = body[1].y;
        st.body_move = 0; st.step = 0;
        for(int i=2; i<=L; ++i) {
            for(int j=0; j<4; ++j) {
                x = body[i-1].x + dx[j];
                y = body[i-1].y + dy[j];
                if(x == body[i].x && y == body[i].y) 
                    st.body_move |= j<<((i-2)*2);
            }
        }
        printf("Case %d: %d\n", ++cas, bfs(st));
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值