推箱子是一个很经典的游戏.今天我们来玩一个简单版本.在一个M*N的房间里有一个箱子和一个搬运工,搬运工的工作就是把箱子推到指定的位置,注意,搬运工只能推箱子而不能拉箱子,因此如果箱子被推到一个角上(如图2)那么箱子就不能再被移动了,如果箱子被推到一面墙上,那么箱子只能沿着墙移动.
现在给定房间的结构,箱子的位置,搬运工的位置和箱子要被推去的位置,请你计算出搬运工至少要推动箱子多少格.
Input
输入数据的第一行是一个整数T(1<=T<=20),代表测试数据的数量.然后是T组测试数据,每组测试数据的第一行是两个正整数M,N(2<=M,N<=7),代表房间的大小,然后是一个M行N列的矩阵,代表房间的布局,其中0代表空的地板,1代表墙,2代表箱子的起始位置,3代表箱子要被推去的位置,4代表搬运工的起始位置.
Output
对于每组测试数据,输出搬运工最少需要推动箱子多少格才能帮箱子推到指定位置,如果不能推到指定位置则输出-1.
Sample Input
1
5 5
0 3 0 0 0
1 0 1 4 0
0 0 1 0 0
1 0 2 0 0
0 0 0 0 0
Sample Output
4
- 第一波错误原因: 误以为箱子目标点的反方向为 !1 即可,例如下面的情况满足该条件,但是人是不能到达的,也不行
0 0 0 0 0
1 1 1 0 0
0 0 2 0 0
1 1 1 0 4
0 3 0 0 0
- 第二波错误原因:然后想先搜一次人能到达的位置,结果还是不对
- 网上一搜多说是水题,而我WA的潇潇洒洒
- 正解:在每次推盒子的时候都进行一次搜索判断人是否能到达
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define MAX_N 10
#define mm(a,b) memset(a,b,sizeof(a))
struct Node{
int px,py;
int x,y;
int step;
};
int N,M,T;
int vis[MAX_N][MAX_N];
int iCan[MAX_N][MAX_N][MAX_N][MAX_N]; //iCan[x1][y1][x2][y2] -> 从(x2,y2) -> (x1,y1) 是否走过
int map[MAX_N][MAX_N];
int sx,sy,psx,psy;
int mov[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
void dfs(int x,int y){
for(int i = 0;i < 4;++i){
int tx = x + mov[i][0];
int ty = y + mov[i][1];
if(tx >= 0 && tx <N && ty >= 0 && ty < M && map[tx][ty] != 1 && !vis[tx][ty]){
vis[tx][ty] = 1;
dfs(tx,ty);
}
}
}
int bfs(){
//初始化
mm(iCan, 0);
queue<Node>que;
Node head;
head.x=sx;
head.y=sy;
head.step=0;
head.px=psx;
head.py=psy;
que.push(head);
//队列不空
while(!que.empty()){
//取队首
head = que.front();
que.pop();
//访问初始化
mm(vis, 0);
vis[head.px][head.py]=1;
vis[head.x ][head.y ]=1;
dfs(head.px,head.py); //人可以到达的点
for(int i=0;i<4;++i){ //拓展
int tx = head.x + mov[i][0]; //下一个点的 x,y
int ty = head.y + mov[i][1];
int x1 = head.x - mov[i][0]; //箱子之后的那个点的 x,y
int y1 = head.y - mov[i][1];
if(tx>=0 && tx<N && ty>=0 && ty<M && map[tx][ty] != 1){ //满足条件
if(x1>=0 && x1<N && y1>=0 && y1<M && vis[x1][y1]){ //箱子之后的那个点是否为空地
if(iCan[head.x][head.y][x1][y1]) continue;
iCan[head.x][head.y][x1][y1]=1;
Node tail; //下一个压入队列
tail.x = tx;
tail.y = ty;
tail.step = head.step+1;
if(map[tx][ty] == 3) return tail.step; //到达终点
tail.px = x1;
tail.py = y1;
que.push(tail);
}
}
}
}
return -1;
}
int main(){
scanf("%d",&T);
while(T--){
cin>>N>>M;
for(int i = 0;i < N;++i){
for(int j = 0;j < M;++j){
scanf("%d",&map[i][j]);
if(map[i][j]==2){ //箱子起点
sx=i;
sy=j;
}
else if(map[i][j]==4){ //人的起点
psx=i;
psy=j;
}
}
}
cout<<bfs()<<endl;
}
return 0;
}