1254推箱子
文章目录
题意:
思路:
箱子的移动按照正常的BFS拓展即可。
重点在于判断搬运工能否把箱子往某个方向推:
- 显然,箱子需要移动到 ( x + 1 , y ) (x+1,y) (x+1,y),搬运工需要移动到 ( x − 1 , y ) (x-1,y) (x−1,y)
- 箱子所在的位置对搬运工来说是无法跨越的障碍。
- 搬运工能否到达目标地并不能简单的判断,需要再用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;
}