推箱子
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4712 Accepted Submission(s): 1329
Problem Description
推箱子是一个很经典的游戏.今天我们来玩一个简单版本.在一个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
Author
Ignatius.L & weigang Lee
解题思路:对箱子进行BFS,还要对人能否移动到推箱子的地方进行BFS。注意标记。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int N = 10;
struct Point{
int x, y;
int u, v;
int step;
}start, fr, next;
struct People{
int mx, my;
}cur, tmp;
int vis1[N][N][4];
int vis2[N][N];
int mp[N][N];
int dir[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1};
int n, m;
int ex, ey;
int flag;
int pbfs(int sx, int sy){
queue<People> que;
cur.mx = sx;
cur.my = sy;
que.push(cur);
while(!que.empty()){
cur = que.front();
que.pop();
if(cur.mx== ex && cur.my == ey){
return 0;
}
for(int i = 0; i < 4; i++){
int tx = cur.mx + dir[i][0], ty = cur.my + dir[i][1];
if(mp[tx][ty] == -1 || mp[tx][ty] == 1 || (tx == fr.x && ty == fr.y)) continue;
if(!vis2[tx][ty]){
vis2[tx][ty] = 1;
tmp.mx = tx;
tmp.my = ty;
que.push(tmp);
}
}
}
return 1;
}
void bfs(){
queue<Point> Q;
Q.push(start);
while(!Q.empty()){
fr = Q.front();
Q.pop();
// cout << fr.x << " " << fr. y << endl;
if(mp[fr.x][fr.y] == 3){
printf("%d\n", fr.step);
return;
}
for(int i = 0; i < 4; i++){
int xx = fr.x + dir[i][0];
int yy = fr.y + dir[i][1];
if(mp[xx][yy] == 1 || mp[xx][yy] == -1) continue;
ex = fr.x + dir[(i + 2) % 4][0];
ey = fr.y + dir[(i + 2) % 4][1];
if(mp[ex][ey] == 1 || mp[ex][ey] == -1) continue;
memset(vis2, 0, sizeof(vis2));
vis2[fr.u][fr.v] = 1;
if(pbfs(fr.u, fr.v)) continue;
// cout << fr.u << " " << fr.v << " " << ex << " " << ey << endl;
if(!vis1[xx][yy][i]){
vis1[xx][yy][i] = 1;
next.x = xx;
next.y = yy;
next.u = fr.x;
next.v = fr.y;
next.step = fr.step + 1;
// cout << xx << " " << yy << " " << next.u << " " << next.v << endl;
Q.push(next);
}
}
}
puts("-1");
return;
}
int main(){
int T;
scanf("%d", &T);
while(T--){
scanf("%d%d", &n, &m);
memset(mp, -1, sizeof(mp));
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++){
scanf("%d", &mp[i][j]);
if(mp[i][j] == 2){
start.x = i;
start.y =j;
}
else if(mp[i][j] == 4){
start.u = i;
start.v = j;
start.step = 0;
}
}
memset(vis1, 0, sizeof(vis1));
bfs();
}
return 0;
}
/*
4 3
3 0 0
1 0 1
4 2 0
0 0 0
6 3
0 0 0
0 0 0
1 0 0
0 0 1
0 2 3
1 4 1
*/
本文介绍了一种经典的推箱子游戏的解决方案,通过BFS算法计算将箱子推到目标位置所需的最少步数。文章详细解释了如何对箱子和人的移动路径进行搜索,并提供了完整的C++实现代码。
268

被折叠的 条评论
为什么被折叠?



