时限: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;
char maze[10][10];
int vis[10][10][10][10];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
int px,py,tx,ty,fx,fy;
struct node{
int px;
int py;
int tx;
int ty;
node(int px = 0,int py = 0,int tx = 0,int ty = 0)
:px(px),py(py),tx(tx),ty(ty){};
};
int bfs();
int main()
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
cin >> maze[i][j];
if(maze[i][j] == '2')
{
tx = i;
ty = j;
maze[i][j] = '0';
}
if(maze[i][j] == '3')
{
fx = i;
fy = j;
maze[i][j] = '0';
}
if(maze[i][j] == '4')
{
px = i;
py = j;
maze[i][j] = '0';
}
}
}
cout << bfs() << endl;
return 0;
}
int bfs()
{
queue<node>q;
node s = node(px,py,tx,ty);
q.push(s);
vis[px][py][tx][ty] = 0;
while(!q.empty())
{
s = q.front();
if(s.tx == fx && s.ty == fy)
{
return vis[s.px][s.py][s.tx][s.ty];
}
q.pop();
for(int i = 0;i < 4;i++)
{
int npx = s.px + dir[i][0];
int npy = s.py + dir[i][1];
if(npx == s.tx && npy == s.ty)
{
int ntx = s.tx + dir[i][0];
int nty = s.ty + dir[i][1];
if(ntx >= 0&&ntx < 10&&nty >= 0&&nty < 10&&!vis[npx][npy][ntx][nty]&&maze[ntx][nty] == '0')
{
q.push(node(npx,npy,ntx,nty));
vis[npx][npy][ntx][nty] = vis[s.px][s.py][s.tx][s.ty] + 1;
}
}
else if(npx >= 0&&npx < 10&&npy >= 0&&npy < 10&&!vis[npx][npy][s.tx][s.ty]&&maze[npx][npy] == '0')
{
q.push(node(npx,npy,s.tx,s.ty));
vis[npx][npy][s.tx][s.ty] = vis[s.px][s.py][s.tx][s.ty] + 1;
}
}
}
return -1;
}