1326.推箱子
时限: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;
int map[10][10];
struct state
{
int bx,by;//box
int px,py;//person
int useful;
};
queue<state> q;
state start;
int tx,ty;
int used[10][10][10][10];
int step[10][10][10][10];
int walk[4][2]= //走一步后的新坐标变化
{
0, -1, //左
+1, 0, //下
0, +1, //右
-1, 0 //上
};
void init();
int bfs();
state move(state now,int i);
void init()
{
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
map[i][j]=cin.get()-'0';
//cout<<map[i][j];
switch(map[i][j])
{
case 2:
{
start.bx=i;
start.by=j;
map[i][j]=0;
break;
}
case 3:
{
tx=i;
ty=j;
map[i][j]=0;
break;
}
case 4:
{
start.px=i;
start.py=j;
map[i][j]=0;
break;
}
default:break;
}
}
cin.get();
}
used[start.bx][start.by][start.px][start.py]=1;
step[start.bx][start.by][start.px][start.py]=0;
q.push(start);
// cout<<endl;
// for(int i=0;i<10;i++)
// {
// for(int j=0;j<10;j++)
// cout<<map[i][j];
// cout<<endl;
// }
}
int bfs()
{
state now,next;
while(!q.empty())
{
now=q.front();
// cout<<now.bx<<" "<<now.by<<" "<<now.px<<" "<<now.py<<" ";
q.pop();
for(int i=0;i<4;i++)
{
next=move(now,i);
if(next.useful)
{
if(next.bx==tx && next.by==ty)
{
return step[next.bx][next.by][next.px][next.py];
}
else
{
q.push(next);
}
}
}
}
return -1;
}
state move(state now,int i)
{
state next;
next.bx=now.bx;
next.by=now.by;
next.px=now.px+walk[i][0];
next.py=now.py+walk[i][1];
// cout<<now.bx<<now.by<<now.px<<now.py<<endl;
// cout<<next.bx<<next.by<<next.px<<next.py<<endl;
if(next.px==next.bx && next.py==next.by)
{
next.bx+=walk[i][0];
next.by+=walk[i][1];
}
next.useful=0;
if(next.bx>=0&&next.bx<10&&next.by>=0&&next.by<10
&&next.px>=0&&next.px<10&&next.py>=0&&next.py<10)
{
if(map[next.bx][next.by]==0 && map[next.px][next.py]==0)
{
if(used[next.bx][next.by][next.px][next.py]==0)
{
next.useful=1;
used[next.bx][next.by][next.px][next.py]=1;
step[next.bx][next.by][next.px][next.py]=
step[now.bx][now.by][now.px][now.py]+1;
}
}
}
return next;
}
int main()
{
init();
cout<<bfs()<<endl;
return 0;
}