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
这是一道典型的搜索题,题意很简单,就是把箱子推到终点需要做的最小步数,但是限制条件很多
比如箱子前面不能使墙,箱子到达的点下一步是否能继续走等等
首先要搜索人走的路径,然后判断人推箱子能走的路径,重点是判断人能不能将箱子往下推
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
using namespace std;
int map[10][10];
int vis[10][10][4], ur[10][10];
int dir[4][2] = { 0,1,0,-1,1,0,-1,0 };
int n, m;
struct node
{
int x, y;//箱子起始
int xx, yy;//人起始
int t;//步数
}st, ed;
struct edg
{
int x, y;
}a, b, c;
queue<node>q;
void Bfs()//搜索人推箱子能走的路径
{
queue<edg>qq;
memset(ur, 0, sizeof(ur));
qq.push(a);
while (!qq.empty())
{
a = qq.front();
qq.pop();
for (int i = 0; i < 4; i++)
{
int xx = a.x + dir[i][0];
int yy = a.y + dir[i][1];
if (xx >= 0 && xx < n&&yy >= 0 && yy < m)//判断边界
{
if (xx == st.x&&yy == st.y)//判断箱子和人是否在一点上
{
int x = st.x + dir[i][0];
int y = st.y + dir[i][1];
if (x >= 0 && x < n&&y >= 0 && y < m)//判断推箱子后是否超出边界
{
if (!vis[x][y][i] && map[x][y] != 1)//如果没有走过且下一步不是墙
{
ed.x = x;
ed.y = y;
ed.xx = xx;
ed.yy = yy;
ed.t = st.t + 1;
q.push(ed);
vis[x][y][i] = 1;
}
}
}
else if (!ur[xx][yy] && map[xx][yy] != 1)//如果所在点不是箱子,继续搜
{
ur[xx][yy] = 1;
c.x = xx;
c.y = yy;
qq.push(c);
}
}
}
}
return;
}
void bfs()//搜索箱子的路径
{
while (q.size()) q.pop();
q.push(st);
while (!q.empty())
{
st = q.front();
q.pop();
if (map[st.x][st.y] == 3)
{
printf("%d\n", st.t);
return;
}
a.x = st.xx;
a.y = st.yy;
Bfs();
}
printf("-1\n");
return;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &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)
{
st.x = i, st.y = j;
}
if (map[i][j] == 4)
{
st.xx = i, st.yy = j;
}
}
st.t = 0;
memset(vis, 0, sizeof(vis));
bfs();
}
}