题目描述
立体推箱子是一个风靡世界的小游戏。
游戏地图是一个N行M列的矩阵,每个位置可能是硬地(用”.”表示)、易碎地面(用”E”表示)、禁地(用”#”表示)、起点(用”X”表示)或终点(用”O”表示)。
你的任务是操作一个1×1×2的长方体。
这个长方体在地面上有两种放置形式,“立”在地面上(1×1的面接触地面)或者“躺”在地面上(1×2的面接触地面)。
在每一步操作中,可以按上下左右四个键之一。
按下按键之后,长方体向对应的方向沿着棱滚动90度。
任意时刻,长方体不能有任何部位接触禁地,并且不能立在易碎地面上。
字符”X”标识长方体的起始位置,地图上可能有一个”X”或者两个相邻的”X”。
地图上唯一的一个字符”O”标识目标位置。
求把长方体移动到目标位置(即立在”O”上)所需要的最少步数。
在移动过程中,”X”和”O”标识的位置都可以看作是硬地被利用。
样例
输入样例:
7 7
#######
#..X###
#..##O#
#....E#
#....E#
#.....#
#######
0 0
输出样例:
10
算法1
(宽搜)
int d[3][4][3] = {
{{-2, 0, 2}, {0, 1, 1}, {1, 0, 2}, {0, -2, 1}},
{{-1, 0, 1}, {0, 2, 0}, {1, 0, 1}, {0, -1, 0}},
{{-1, 0, 0}, {0, 1, 2}, {2, 0, 0}, {0, -1, 2}}
};
d[3][4][3]
最后一个维度表示三个分量,这三个分量代表x, y, 当前是立着,横躺,竖躺。
第二个维度4, 表示当前一个状态可以往上, 往右, 往下, 往左, 四个方向变化。
第一个维度3, 表示当前状态是 立着,横躺,竖躺。
时间复杂度
参考文献
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 510;
struct State{
int x, y, lie;// 0立着,1横着躺,2竖着躺
};
int n, m;
char g[N][N];
int dist[N][N][3];
bool check(int x, int y){
if (x < 0 || x >= n || y < 0 || y >= m) return false;
return g[x][y] != '#';
}
int bfs(State start, State end){
queue<State> q;
memset(dist, -1, sizeof dist);
dist[start.x][start.y][start.lie] = 0;
q.push(start);
int d[3][4][3] = {
{{-2, 0, 2}, {0, 1, 1}, {1, 0, 2}, {0, -2, 1}},
{{-1, 0, 1}, {0, 2, 0}, {1, 0, 1}, {0, -1, 0}},
{{-1, 0, 0}, {0, 1, 2}, {2, 0, 0}, {0, -1, 2}}
};
while (q.size()){
auto t = q.front(); q.pop();
for (int i = 0; i < 4; i ++){//因为当前的状态只能往四个方向变化,所以循环4次。
State next = {t.x + d[t.lie][i][0], t.y + d[t.lie][i][1], d[t.lie][i][2] };
int x = next.x, y = next.y;
if (!check(x, y)) continue;
if (next.lie == 0){
if (g[x][y] == 'E') continue;
}else if (next.lie == 1){
if (!check(x, y + 1)) continue;
}else{
if (!check(x + 1, y)) continue;
}
if (dist[next.x][next.y][next.lie] == -1){
dist[next.x][next.y][next.lie] = dist[t.x][t.y][t.lie] + 1;
q.push(next);
}
}
}
return dist[end.x][end.y][end.lie];
}
int main(){
while (scanf("%d%d", &n, &m), n || m){
for (int i = 0; i < n; i ++ ) scanf("%s", g[i]);
State start {-1}, end;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
if (g[i][j] == 'X' && start.x == -1){
if (g[i + 1][j] == 'X') start = {i, j, 2};
else if (g[i][j + 1] == 'X') start = {i, j, 1};
else start = {i, j, 0};
}else if (g[i][j] == 'O') end = {i, j, 0};
int res = bfs(start, end);
if (res == -1) puts("Impossible");
else printf("%d\n", res);
}
return 0;
}