poj 1475 uva 589 - Pushing Boxes

题目大意

人推箱子从起点到终点,要求推箱子的次数最少,并打印出来人移动的路径。

题目分析

对于箱子进行宽搜的同时,要兼顾人是否能够把箱子推到相应的位置

每一次对箱子bfs 然后对人再bfs

#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
const int dir[4][2] = {{-1,0},{1,0},{0,1},{0,-1}};
const char dirman[4] = {'n','s','e','w'};
const char dirbox[4] = {'N','S','E','W'};

char a[21][21];
int r, c;

struct node
{
int manx,many;
int boxx,boxy;
string path;
node():path("") {}
node(int _manx,int _many,int _boxx,int _boxy ,string &_path):manx(_manx),many(_many),boxx(_boxx),boxy(_boxy),path(_path) {}

};
struct pos
{
int x,y;
string path;
pos():path("") {}
pos(int _x, int _y) : x(_x), y(_y), path("") {}
pos(int _x,int _y,string &_path):x(_x),y(_y),path(_path) {}
};
bool judge(int x,int y)
{
if(x>0&&x<=r&&y>0&&y<=c&&a[x][y]!='#')
return true ;
return false;
}
bool bfsman(string &path ,pos st,pos ed)
{
bool vis[21][21];
memset(vis,false,sizeof(vis));
queue<pos> q;
q.push(st);
vis[st.x][st.y]=true;
while(!q.empty())
{
pos s=q.front();
q.pop();
if(s.x==ed.x&&s.y==ed.y)
{
path=s.path;
return true;
}

for(int i=0; i<4; i++)
{
int x=s.x+dir[i][0];
int y=s.y+dir[i][1];
string p = s.path + dirman[i];
if(judge(x,y)&&!vis[x][y])
{
q.push(pos(x,y,p));
vis[x][y]=true;

}
}
}
return false;
}
bool bfsbox(string &path,node s,pos t)
{
bool vist[23][23];
memset(vist,false,sizeof(vist));
vist[s.boxx][s.boxy]=true;
queue<node> Q;
Q.push(s);
while(!Q.empty())
{
//printf("==\n");
node st=Q.front();
Q.pop();
if(st.boxx==t.x&&st.boxy==t.y)
{
path=st.path;
//cout<<path<<endl;
return true;
}
a[st.boxx][st.boxy]='#';
for(int i=0; i<4; i++)
{
int x=st.boxx+dir[i][0];
int y=st.boxy+dir[i][1];
int x_=st.boxx-dir[i][0];
int y_=st.boxy-dir[i][1];
if(!vist[x][y]&&judge(x,y)&&judge(x_,y_))
{
string pathman="";
if(bfsman(pathman,pos(st.manx,st.many),pos(x_,y_)))
{
vist[x][y]=true;
string p=st.path+pathman+dirbox[i];
Q.push(node(st.boxx, st.boxy, x, y, p));
}
}

}
a[st.boxx][st.boxy]='.';
}
return false;
}
int main()
{
int cases=0;
while(scanf("%d%d",&r,&c)!=EOF)
{
if(c==0&r==0)
break;
node s;
pos t;
for(int i=1; i<=r; i++)
{
scanf("%s",&a[i][1]);
for(int j=1; j<=c; j++)
{
if(a[i][j]=='T')
{
t.x=i;
t.y=j;
}
if(a[i][j]=='B')
{
s.boxx=i;
s.boxy=j;
}
if(a[i][j]=='S')
{
s.manx=i;
s.many=j;
}
}
}
string path="";
if (bfsbox(path, s, t))
printf("Maze #%d\n%s\n\n", ++cases, path.c_str());
else
printf("Maze #%d\nImpossible.\n\n", ++cases);
}
return 0;
}

posted on 2015-03-25 19:09  tsw123  阅读(165)  评论(0编辑  收藏  举报

导航