Author
Ignatius.L & weigang Lee
看到网上有用双重bfs,感觉挺麻烦的。。。然后用的一个bfs就搞定了。。用一个4维标记数组,标记人跟箱子是否走过这个点。
用优先队列记录步数最小的路径,到达终点后一定是最小的步数。按照人的视角进行bfs,反正碰到箱子就正常地向你走的方向推,判断一下是否越界就行了。
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <cmath>
#include <stdio.h>
using namespace std;
struct node {
int px, py;//people_position
int bx, by;//bos_position
int step;
bool operator < (const node& n) const {
return step >= n.step;
}
void set(int x1, int y1, int x2, int y2, int s = 0) {
px = x1, py = y1, bx = x2, by = y2, step = s;
}
};
int N, M;
int start_px, start_py, end_x, end_y;
int start_bx, start_by;
int visited[10][10][10][10];
int map[10][10];
int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
inline void set_visited(const node& n) {//设为已访问
visited[n.px][n.py][n.bx][n.by] = 1;
}
inline bool check(int x, int y) {//检查是否越界
if (x <= 0 || x > N || y > M || y <= 0 || map[x][y] == 1)
return false;
return true;
}
inline void init() {
memset(visited, 0, sizeof(visited));
memset(map, 0, sizeof(map));
}
int bfs() {
priority_queue<node> que;
node cur, nex;
cur.set(start_px, start_py, start_bx, start_by, 0);
que.push(cur);
set_visited(cur);
while (!que.empty()) {
cur = que.top();
que.pop();
//cout << cur.px << " " << cur.py << " " << cur.bx << " " << cur.by << " " << cur.step << endl;
for (int i = 0; i < 4; ++i) {
nex.set(cur.px + dir[i][0], cur.py + dir[i][1], cur.bx, cur.by, cur.step);
if (nex.px == nex.bx && nex.py == nex.by) {//人走到了箱子上(推箱子
nex.bx += dir[i][0];
nex.by += dir[i][1];
if (check(nex.bx, nex.by) && !visited[nex.px][nex.py][nex.bx][nex.by]) {
nex.step++;
if (nex.bx == end_x && nex.by == end_y) {
return nex.step;
}
set_visited(nex);
que.push(nex);
}
} else {
if (check(nex.px, nex.py) && !visited[nex.px][nex.py][nex.bx][nex.by]) {
set_visited(nex);
que.push(nex);
}
}
}
}
return -1;
}
int main() {
int t;
cin >> t;
while (t--) {
init();
cin >> N >> M;
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= M; ++j) {
cin >> map[i][j];
if (map[i][j] == 4) {
start_px = i;
start_py = j;
} else if (map[i][j] == 2) {
start_bx = i;
start_by = j;
} else if (map[i][j] == 3) {
end_x = i;
end_y = j;
}
}
}
cout << bfs() << endl;
}
}
|