题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1254
题目:
推箱子是一个很经典的游戏.今天我们来玩一个简单版本.在一个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
题解:bfs+bfs,不得不说,这是一道好题。第一个bfs是用来遍历箱子所走的方向,第二个bfs用来判断搬运工是否可以到达箱子所走的反方向的位置(因为推箱子的话,搬运工需要在箱子后面)。需要注意的是判断的时候需要标记箱子的位置,判断完之后再还原标记。还有的就是,箱子可以走已经走过的路,这也是这道题有意思的地方。比较巧妙的方法就是判断方格是否走过两次。
代码及注释如下:
#include<iostream>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
struct box_move {//箱子
int x,y,wx,wy,step;//x y 为箱子当前位置 wx wy 为工人当前位置
friend bool operator <(box_move a,box_move b) {
return a.step>b.step;
}
};
struct work {//工人
int x,y;//只需要判断是否可以到达指定位置,无需step
};
int map[8][8],book[8][8],vis[8][8],n,m,ex,ey;
int bfs_move(int x,int y,int nx,int ny) {//x,y为搬运工的目的位置
queue<work> man;
man.push(work{nx,ny});//搬运工初始位置
int next[4][2]={1,0,0,1,-1,0,0,-1};//四个方向
while(!man.empty()) {
work tmp;
tmp = man.front();man.pop();
if(tmp.x==x&&tmp.y==y) return false;//可以到达
for(int i=0;i<4;i++) {
int tx = tmp.x + next[i][0];
int ty = tmp.y + next[i][1];
if(tx<1||tx>m||ty<1||ty>n) continue;//越界
if(map[tx][ty]==-1||book[tx][ty]) continue;//墙或已走过
man.push(work{tx,ty});
book[tx][ty]=1;//标记走过的格子
}
}
return true;
}
int bfs(int sx,int sy,int wx,int wy) {//箱子
priority_queue<box_move> q;
q.push(box_move{sx,sy,wx,wy,0});
int next[4][2]={1,0,0,1,-1,0,0,-1};
while(!q.empty()) {
box_move tmp;
tmp = q.top();q.pop();
if(tmp.x == ex && tmp.y == ey)
return tmp.step;//箱子到达终点位置
for(int i=0;i<4;i++) {
int tx = tmp.x + next[i][0];
int ty = tmp.y + next[i][1];
int man_x = tmp.x - next[i][0];//工人目的点
int man_y = tmp.y - next[i][1];
if(tx<1||tx>m||ty<1||ty>n) continue;//越界
if(map[tx][ty]==-1||vis[tx][ty]>2) continue;//重点!!!
if(map[man_x][man_y]==-1) continue;//搬运工目的地为墙
memset(book,0,sizeof(book));//book用来标记搬运工走过的格子
book[tmp.x][tmp.y]=1;//标记箱子的位置
if(bfs_move(man_x,man_y,tmp.wx,tmp.wy)) continue;//判断是否可以到达
book[tmp.x][tmp.y]=0;//还原
q.push(box_move{tx,ty,man_x,man_y,tmp.step+1});
vis[tx][ty]++;
}
}
return -1;//不能到达终点
}
int main() {
int T;
ios::sync_with_stdio(false);
cin>>T;
while(T--) {
cin>>m>>n;//m行n列
int tmp,sx,sy,wx,wy;
memset(vis,0,sizeof(vis));//vis用来标记箱子走过的格子
for(int i=1;i<=m;i++) {
for(int j=1;j<=n;j++) {
cin>>tmp;
map[i][j]=0;
if(tmp==1) map[i][j]=-1;
else if(tmp==2) sx=i,sy=j;//箱子起点位置
else if(tmp==3) ex=i,ey=j;//箱子终点位置
else if(tmp==4) wx=i,wy=j;//搬运工初始位置
}
}
cout<<bfs(sx,sy,wx,wy)<<endl;
}
return 0;
}