推箱子noj
描述:
绝大多数人都玩过推箱子的游戏,控制一个人将箱子推动到目标位置即获得胜利。现请你编写一个程序,判断将箱子推到目标位置至少需要多少步。
输入:
推箱子的平面区域为固定大小(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 Node {
int bx, by;
int rx, ry;
int step;
Node(int _bx, int _by, int _rx, int _ry,int _step)
{
bx = _bx;
by = _by;
rx = _rx;
ry = _ry;
step = _step;
}
};
int tx, ty, bx, by, rx, ry;//目标位置
int maze[10][10];
int flag[10][10][10][10];
int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
void bfs();
int main()
{
char x;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
cin >> x;
switch (x)
{
case '1':
maze[i][j] = 1;//墙
break;
case '2'://箱子
bx = i;
by = j;
break;
case '3'://目标
tx = i;
ty = j;
break;
case '4'://人
rx = i;
ry = j;
break;
}
}
}
bfs();
return 0;
}
void bfs()
{
Node next(0, 0, 0, 0, 0);
Node now(bx, by, rx, ry, 0);
queue<Node>q;
q.push(now);
while (!q.empty()) {
now = q.front();
q.pop();
if (now.bx == tx && now.by == ty) {
cout << now.step << endl;
return;
}
if (flag[now.bx][now.by][now.rx][now.ry])continue;//重复
flag[now.bx][now.by][now.rx][now.ry] = 1;
for (int i = 0; i < 4; i++) {
next.rx = now.rx + dir[i][0];
next.ry = now.ry + dir[i][1];
if (next.rx >= 0 && next.rx < 10 && next.ry >= 0 && next.ry < 10 && !maze[next.rx][next.ry]) {
if (next.rx == now.bx && next.ry == now.by) {//可以推箱子
next.bx = next.rx + dir[i][0];
next.by = next.ry + dir[i][1];
if (next.bx >= 0 && next.bx < 10 && next.by >= 0 && next.by < 10 && !maze[next.bx][next.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);
}
}
}
}
cout << "-1" << endl;
}