hdu.1254.推箱子(bfs + 优先队列)

时间:2023-01-09 22:36:16

推箱子

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 6021    Accepted Submission(s): 1718

Problem Description
推箱子是一个很经典的游戏.今天我们来玩一个简单版本.在一个M*N的房间里有一个箱子和一个搬运工,搬运工的工作就是把箱子推到指定的位置,注意,搬运工只能推箱子而不能拉箱子,因此如果箱子被推到一个角上(如图2)那么箱子就不能再被移动了,如果箱子被推到一面墙上,那么箱子只能沿着墙移动.
现在给定房间的结构,箱子的位置,搬运工的位置和箱子要被推去的位置,请你计算出搬运工至少要推动箱子多少格.hdu.1254.推箱子(bfs + 优先队列)
 
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<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
int T ;
int n , m ;
const int M = ;
int map[M][M] ;
bool vis[M][M][M][M] ;
int move[][] = {{,} , {- , } , {,} , { , -} } ;
struct node
{
int x , y ;
int a , b ;
int time ;
bool operator < (const node &rhs ) const
{
return time > rhs.time ;
}
}; int bfs (int sx , int sy , int mx , int my , int ex , int ey)
{
//printf ("Last---> (%d,%d)\n" , ex , ey ) ;
node ans , tmp ;
std::priority_queue<node> q ;
memset (vis , , sizeof(vis)) ;
while ( !q.empty ()) q.pop () ;
q.push ( (node) {sx , sy , mx , my , }) ;
vis[sx][sy][mx][my] = ;
if (mx == ex && my == ey) return ;
while ( !q.empty ()) {
ans = q.top () ; q.pop () ;
// printf ("S----(%d,%d) tui (%d,%d)\n" , ans.x , ans.y , ans.a , ans.b ) ;
for (int i = ; i < ; i ++) {
tmp = ans ;
tmp.x += move[i][] ; tmp.y += move[i][] ;
if (tmp.x < || tmp.y < || tmp.x == n || tmp.y == m) continue ;
if (map[tmp.x][tmp.y] == ) continue ;
if (tmp.x == tmp.a && tmp.y == tmp.b ) {
int x = tmp.x + move[i][] , y = tmp.y + move[i][] ;
if (x < || y < || x == n || y == m) continue ;
if (map[x][y] == ) continue ;
tmp.a = x , tmp.b = y ;
tmp.time ++ ;
}
if (vis[tmp.x][tmp.y][tmp.a][tmp.b]) continue ;
vis[tmp.x][tmp.y][tmp.a][tmp.b] = ;
q.push (tmp ) ;
// printf ("(%d,%d) tui (%d,%d)\n" , tmp.x , tmp.y , tmp.a , tmp.b ) ;
if (tmp.a == ex && tmp.b == ey) return tmp.time ;
}
}
return - ;
} int main ()
{
//freopen ("a.txt" , "r" , stdin ) ;
scanf ("%d" , &T ) ;
while (T --) {
scanf ("%d%d" , &n , &m ) ;
int k ;
int sx , sy , ex , ey , mx , my ;
for (int i = ; i < n ; i ++) for (int j = ; j < m ; j ++) scanf ("%d" , &map[i][j]) ;
for (int i = ; i < n ; i ++) {
for (int j = ; j < m ; j ++) {
if (map[i][j] == ) sx = i , sy = j ;
else if (map[i][j] == ) mx = i , my = j ;
else if (map[i][j] == ) ex = i , ey = j ;
}
}
if ( (k = bfs (sx , sy , mx , my , ex , ey )) == -) puts ("-1") ;
else printf ("%d\n" , k ) ;
}
return ;
}
[ Copy to Clipboard ] [ Save to File]