BFS——1254推箱子

1254推箱子

请添加图片描述

文章目录


题意:

在这里插入图片描述

思路:

箱子的移动按照正常的BFS拓展即可。
重点在于判断搬运工能否把箱子往某个方向推:

  1. 显然,箱子需要移动到 ( x + 1 , y ) (x+1,y) (x+1,y),搬运工需要移动到 ( x − 1 , y ) (x-1,y) (x1,y)
  2. 箱子所在的位置对搬运工来说是无法跨越的障碍。
  3. 搬运工能否到达目标地并不能简单的判断,需要再用BFS来判断可行性(总的来说,出现了BFS套BFS)。

此外,标记数组也应该得到修改,因为搬运工在不同的位置,会对上述可行性的判断产生影响,所以标记数组除了箱子的位置,还有搬运工的位置,标记数组需要有四维。

AC代码:
在这里插入图片描述

#include<bits/stdc++.h>

const int N = 10,M = 2e5+10,INF = 0x3f3f3f3f;
struct Node{
    int x,y,px,py,step;
};
int n,m,start_x,start_y,end_x,end_y,p_x,p_y;
int a[N][N];
int ne[4][2] = {1,0,0,1,-1,0,0,-1};
bool book[N][N][N][N],vis[N][N];

bool OK(int x1,int y1,int x2,int y2)
{
    memset(vis,false,sizeof vis);
    std::queue<std::pair<int,int>> que;
    vis[x1][y1] = true;
    que.push({x1,y1});
    while(!que.empty())
    {
        auto temp = que.front();
        que.pop();
        if(temp.first == x2 && temp.second == y2)return true;
        for(int i = 0 ; i < 4 ; i++)
        {
            int tx = temp.first + ne[i][0];
            int ty = temp.second + ne[i][1];
            if(tx<1||ty<1||tx>n||ty>m||a[tx][ty]==1||vis[tx][ty])continue;
            vis[tx][ty] = true;
            que.push({tx,ty});
        }
    }
    return false;
}

void bfs()
{
    std::queue<Node> que;
    que.push({start_x,start_y,p_x,p_y,0});
    book[start_x][start_y][p_x][p_y] = true;
    while(!que.empty())
    {
        auto temp = que.front();
        que.pop();
        if(temp.x == end_x && temp.y == end_y)
        {
            std::cout<<temp.step<<'\n';
            return;
        }
        a[temp.x][temp.y] = 1;
        for(int i = 0 ; i < 4 ; i++)
        {
            int tx = temp.x + ne[i][0];
            int ty = temp.y + ne[i][1];
            if(tx<1||ty<1||tx>n||ty>m||a[tx][ty]==1||book[tx][ty][temp.x][temp.y])continue;
            if(!OK(temp.px,temp.py,temp.x-ne[i][0],temp.y-ne[i][1]))continue;
            que.push({tx,ty,temp.x,temp.y,temp.step+1});
            book[tx][ty][temp.x][temp.y] = true;
        }
        a[temp.x][temp.y] = 0;
    }
    std::cout<<-1<<'\n';
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    int T;
    std::cin>>T;
    while(T--)
    {
        memset(book,false,sizeof book);
        std::cin>>n>>m;
        for(int i = 1 ; i <= n ; i++)
            for(int j = 1 ; j <= m ; j++)
            {
                std::cin>>a[i][j];
                if(a[i][j]==2) start_x = i,start_y = j;
                else if(a[i][j]==3)end_x = i,end_y = j;
                else if(a[i][j]==4)p_x = i,p_y = j;
            }
        bfs();
    }
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值