推箱子
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
*/