hdu 1254 推箱子

推箱子游戏:0代表空的地板,1代表墙,2代表箱子的起始位置,3代表箱子要被推去的位置,4代表搬运工的起始位置.

问你箱子最少移动多少次能到目的位置,如无法到达则输出-1.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
int n, m, a[10][10], move[4][2]={0,1,0,-1,1,0,-1,0}, vis[10][10][10][10], flag[10][10];
struct node{int x, y, px, py, step;}st, end;  //箱子位置x,y,人的位置px,py。
bool dfs(int sx, int sy, int tx, int ty){
    if(sx==tx&&sy==ty)return true;
    for(int i=0; i<4; i++){
        int x1=sx+move[i][0];
        int y1=sy+move[i][1];
        if(x1==0||y1==0||x1>n||y1>m||flag[x1][y1]||a[x1][y1]==1)continue;
        flag[x1][y1]=1;
        if(dfs(x1, y1, tx, ty))return true;
    }
    return false;
}
int bfs(){
    queue<node> q;
    st.step=0;
    q.push(st);
    int i, sx, sy;
    memset(vis, 0, sizeof(vis));
    vis[st.x][st.y][st.px][st.py]=1;
    node head, next;
    while(!q.empty()){
        head=q.front();
        q.pop();
        for(i=0; i<4; i++){
            next.x=head.x+move[i][0];
            next.y=head.y+move[i][1];
            next.px=head.x;
            next.py=head.y;
            next.step=head.step+1;
            if(next.x==0||next.y==0||next.x>n||next.y>m||
               vis[next.x][next.y][head.x][head.y]||a[next.x][next.y]==1)continue;
            sx=head.x-move[i][0];sy=head.y-move[i][1];
            if(sx==0||sy==0||sx>n||sy>m||a[sx][sy]==1)continue;
            a[head.x][head.y]=1;
            memset(flag, 0, sizeof(flag));
            flag[head.px][head.py]=1;
            if(dfs(head.px, head.py, sx, sy)){          //判断搬运工能否到达要推的位置
                vis[next.x][next.y][head.x][head.y]=1;
                if(next.x==end.x&&next.y==end.y){
                    return next.step;
                }
                q.push(next);
            }
            a[head.x][head.y]=0;
        }
    }
    return -1;
}


int main(){
    //freopen("1.txt", "r", stdin);
    int T, i, j;
    scanf("%d", &T);
    while(T--){
        scanf("%d %d", &n, &m);
        for(i=1; i<=n; i++)
        for(j=1; j<=m; j++){
            scanf("%d", &a[i][j]);
            if(a[i][j]==2){
                st.x=i;st.y=j;
            }
            else if(a[i][j]==3){
                end.x=i;end.y=j;
            }
            else if(a[i][j]==4){
                st.px=i;st.py=j;
            }
        }
        printf("%d\n", bfs());
    }
    return 0;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值