题解 UVA589 【Pushing Boxes】
博客食用
这道题,肯定是BFS。
有几个难点:
1.人推箱子的方向
2.判断情况是否成立
怎么同时维护箱子和人的状态呢?考虑使用双重BFS。
首先找到箱子到终点的路径。对于箱子每走一步,找出人原本的位置到推箱子的位置,即为箱子的上下左右。正确的推箱子方向就是与箱子前进的方向相反的方向。这里再套一层BFS。最后把答案记录下来就可以了。
这里要注意一下方向数组,必须要和推箱子方向和字符串一一对应,不然程序就会到处乱走。
AC代码:
#include<bits/stdc++.h>
using namespace std;
struct status
{
int box_x,box_y;
int person_x,person_y;
string ans;
};
int n,m,sx,sy,tx,ty,bx,by;
string tmp;
char E[25][25];
int visA[25][25][4];
int visB[25][25];
int dir[4][2]={-1,0,1,0,0,-1,0,1};
char P[4]={'N','S','W','E'};
char M[4]={'n','s','w','e'};
inline bool pd(int x,int y)
{
if(x>0&&x<=n&&y>0&&y<=m&&E[x][y]!='#')return true;
return false;
}
inline bool bfs_per(status per,status box)
{
tmp="";
status st;
st.box_x=per.person_x;
st.box_y=per.person_y;
st.ans="";
queue<status>q;
memset(visB,0,sizeof(visB));
while(q.size())q.pop();
q.push(st);
while(q.size())
{
status top,nex;
top=q.front();
q.pop();
if(top.box_x==per.box_x&&top.box_y==per.box_y)
{
tmp=top.ans;
return true;
}//到达
for(int i=0;i<4;++i)
{
nex=top;
nex.box_x=top.box_x+dir[i][0];
nex.box_y=top.box_y+dir[i][1];
if(!pd(nex.box_x,nex.box_y)||visB[nex.box_x][nex.box_y])continue;
if(nex.box_x==box.box_x&&nex.box_y==box.box_y)continue;
visB[nex.box_x][nex.box_y]=1;
nex.ans=top.ans+M[i];
q.push(nex);
}
}
return false;
}
inline string bfs_box()
{
memset(visA,0,sizeof(visA));
status st;//下面初始化
st.box_x=bx;
st.box_y=by;
st.person_x=sx;
st.person_y=sy;
st.ans="";
queue<status>q;
while(q.size())q.pop();
q.push(st);
while(q.size())
{
status nex,pre;
status top=q.front();
q.pop();
if(E[top.box_x][top.box_y]=='T')return top.ans;//到达终点
for(int i=0;i<4;++i)
{
nex=top;
nex.box_x=top.box_x+dir[i][0];
nex.box_y=top.box_y+dir[i][1];
if(!pd(nex.box_x,nex.box_y)||visA[nex.box_x][nex.box_y][i])continue;
pre=top;
if(i==0)pre.box_x=top.box_x+1;//寻找人推箱子的位置
if(i==1)pre.box_x=top.box_x-1;
if(i==2)pre.box_y=top.box_y+1;
if(i==3)pre.box_y=top.box_y-1;
if(!bfs_per(pre,top))continue;//如果人到达不了推箱子的位置
visA[nex.box_x][nex.box_y][i]=1;//判断箱子重复路径
nex.ans=top.ans+tmp;//把人的路径累计起来
nex.ans=nex.ans+P[i];
nex.person_x=top.box_x;
nex.person_y=top.box_y;
q.push(nex);//加入队列
}
}
return "Impossible.";
}
int main()
{
while(cin>>n>>m&&n+m)//注意多组数据样例
{
for(int i=1;i<=n;++i)
for(int j=1;j<=m;++j)
{
cin>>E[i][j];
if(E[i][j]=='S')sx=i,sy=j;
if(E[i][j]=='T')tx=i,ty=j;
if(E[i][j]=='B')bx=i,by=j;
}
cout<<bfs_box()<<endl;
}
return 0;
}