Problem G
推箱子
时限:1000ms 内存限制:10000K 总时限:3000ms
描述:
绝大多数人都玩过推箱子的游戏,控制一个人将箱子推动到目标位置即获得胜利。现请你编写一个程序,判断将箱子推到目标位置至少需要多少步。
输入:
推箱子的平面区域为固定大小(10*10),使用10行10列输入推箱子的初始局面。其中,0代表空格,1代表墙,2代表箱子,3代表目标位置,4代表人。
注:游戏中只有一个箱子,一个目标位置,一个人。
输出:
输出将箱子推到目标位置的最小步数;若箱子不可能被推到目标位置,输出-1。
输入样例:
0000000000
0000000300
0100000000
0100000000
0101111100
0000010000
0000010000
0020010040
0000010000
0000010000
输出样例:
34
#include <iostream>
#include <queue>
using namespace std;
struct rec {
int bx, by;
int px, py;
int step;
};
queue<rec> q;
char maze[10][10];
int pstart_x, pstart_y, bstart_x, bstart_y, target_x, target_y;
int visited[10][10][10][10];
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
void init() {
for (int i = 0; i < 10; i++) {
cin >> maze[i];
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (maze[i][j] == '2') {
bstart_x = i, bstart_y = j;
} else if (maze[i][j] == '3') {
target_x = i, target_y = j;
} else if (maze[i][j] == '4') {
pstart_x = i, pstart_y = j;
}
}
}
}
int bfs() {
rec temp;
temp.px = pstart_x, temp.py = pstart_y;
temp.bx = bstart_x, temp.by = bstart_y;
temp.step = 0;
q.push(temp);
while (q.size()) {
rec now = q.front();
// cout << " now.step :" << now.step << endl;
if (now.bx == target_x && now.by == target_y) {
return now.step;
}
q.pop();
if (visited[now.px][now.py][now.bx][now.by] == 1) {
continue;
}
visited[now.px][now.py][now.bx][now.by] = 1;
for (int i = 0; i < 4; i++) {
rec next;
next.px = now.px + dx[i];
next.py = now.py + dy[i];
if (next.py >= 0 && next.py < 10 && next.px >= 0 && next.px < 10 && maze[next.px][next.py] != '1') {
if (next.px == now.bx && next.py == now.by) {
int xx = now.bx + dx[i];
int yy = now.by + dy[i];
if (xx >= 0 && xx <= 9 && yy <= 9 && yy >= 0 && maze[xx][yy] != '1') {
next.bx = xx, next.by = yy;
next.px = now.bx, next.py = now.by;
next.step = now.step + 1;
q.push(next);
}
} else {
next.step = now.step + 1;
next.bx = now.bx, next.by = now.by;
q.push(next);
}
}
}
}
return -1;
}
int main() {
init();
int ans = bfs();
cout << ans << endl;
return 0;
}