推箱子 1 http://acm.hdu.edu.cn/showproblem.php?pid=1254
推箱子 2 http://acm.hzau.edu.cn/problem.php?id=1010
推箱子 3 https://www.bnuoj.com/v3/problem_show.php?pid=33683
一系列搜索的题目
先讲讲第一题,
题目意思:
推箱子是一个很经典的游戏.今天我们来玩一个简单版本.在一个M*N的房间里有一个箱子和一个搬运工,搬运工的工作就是把箱子推到指定的位置,注意,搬运工只能推箱子而不能拉箱子,因此如果箱子被推到一个角上(如图2)那么箱子就不能再被移动了,如果箱子被推到一面墙上,那么箱子只能沿着墙移动.
现在给定房间的结构,箱子的位置,搬运工的位置和箱子要被推去的位置,请你计算出搬运工至少要推动箱子多少格.
Input
输入数据的第一行是一个整数T(1<=T<=20),代表测试数据的数量.然后是T组测试数据,每组测试数据的第一行是两个正整数M,N(2<=M,N<=7),代表房间的大小,然后是一个M行N列的矩阵,代表房间的布局,其中0代表空的地板,1代表墙,2代表箱子的起始位置,3代表箱子要被推去的位置,4代表搬运工的起始位置.
Output
对于每组测试数据,输出搬运工最少需要推动箱子多少格才能帮箱子推到指定位置,如果不能推到指定位置则输出-1.
给一组样例:
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
题目思路:
双广搜,主线按照箱子到终点来搜索,一边搜索一边判断这一步是否可以走?思路挺简单,写起来比较容易吧,给个代码参考,不对还望指出来啊!谢谢了。
#include <cstdio>
#include <cstring>
#include <cctype>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <bitset>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdlib.h>
using namespace std;
typedef long long LL;
const int INF=2e9+1e8;
const double eps=0.0000001;
const int MM=15;
int maze[MM][MM];
bool vis[MM][MM][MM*MM];
int m,n,dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; // m 行 n 列;
struct node
{
int x,y,step;
int px,py;
};
struct point
{
int x,y;
};
bool is_out(int x,int y)
{
if(x>=1&&x<=m&&y>=1&&y<=n) return true;
return false;
}
bool is_arrive(int sx,int sy,int ex,int ey,int xx,int yy)
{
queue<point>q;
bool visit[MM][MM];
memset(visit,0,sizeof(visit));
visit[sx][sy]=1;
point first,second;
first.x=sx,first.y=sy;
q.push(first);
while(!q.empty())
{
first=q.front();
q.pop();
if(first.x==xx&&first.y==yy) continue;
if(first.x==ex&&first.y==ey) return true;
for(int i=0; i<4; i++)
{
int x=first.x+dir[i][0],y=first.y+dir[i][1];
if(is_out(x,y)&&maze[x][y]!=1&&visit[x][y]==0) //
{
visit[x][y]=1;
second.x=x,second.y=y;
q.push(second);
}
}
}
return false;
}
int bfs(int sx,int sy,int px,int py)//对箱子进行广搜
{
memset(vis,0,sizeof(vis));
vis[sx][sy][MM*px+py]=1;
queue<node>q;
node first,second;
first.px=px,first.py=py,first.step=0;
first.x=sx,first.y=sy;
q.push(first);
while(!q.empty())
{
first=q.front();
q.pop();
int x=first.x,y=first.y;
int px=first.px,py=first.py;
if(maze[x][y]==3) return first.step;
for(int i=0; i<4; i++)
{
x=first.x+dir[i][0],y=first.y+dir[i][1];
px=first.x-dir[i][0],py=first.y-dir[i][1];
if(is_out(px,py)&&is_out(x,y)&&maze[x][y]!=1&&maze[px][py]!=1)
{
if(vis[x][y][MM*px+py]==0&&is_arrive(first.px , first.py , px , py , first.x , first.y))
{
vis[x][y][MM*px+py]=1;
second.px=first.x,second.py=first.y;
second.step=first.step+1;
second.x=x,second.y=y;
q.push(second);
}
}
}
}
return -1;
}
int main()
{
int ncase;
scanf("%d",&ncase);
while(ncase--)
{
int i,j,sx,sy,manx,many;
scanf("%d %d",&m,&n);
for(i=1; i<=m; i++)
for(j=1; j<=n; j++)
{
scanf("%d",&maze[i][j]);
if(maze[i][j]==2) sx=i,sy=j;// 箱子起始位置
if(maze[i][j]==4) manx=i,many=j;// 人的气势位置
}
printf("%d\n",bfs(sx,sy,manx,many));
}
return 0;
}