POJ 1475 Pushing Boxes 搜索- 两重BFS

时间:2022-05-19 12:15:17

题目地址: http://poj.org/problem?id=1475

两重BFS就行了,第一重是搜索箱子,第二重搜索人能不能到达推箱子的地方。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <deque>
#include <queue>
#include <iterator>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <cctype>
using namespace std; typedef long long LL;
const int N=21;
const LL II=1000000007; int r,c,begx,begy,endx,endy,begsx,begsy;
char maps[21][21];
int t[4][2]={-1,0,1,0,0,1,0,-1};
char P[4]={'N', 'S', 'E', 'W'};
char M[4]={'n', 's', 'e', 'w'};
int mark[21][21]; struct xhr
{
int x,y;
string ans;
}F,G; struct xhx
{
int bx,by,px,py;
string ans;
}f,g; bool inmap(int x,int y)
{
return x>=1&&x<=r&&y>=1&&y<=c;
} bool ren(int bx,int by,int ex,int ey)//人bfs
{
queue<xhr> P;
bool Mark[21][21];
memset(Mark,0,sizeof(Mark));
Mark[bx][by]=1;
Mark[f.bx][f.by]=1;
F.x=bx; F.y=by;
F.ans="";
if(bx==ex&&by==ey)
return true;
P.push(F);
while(!P.empty())
{
F=P.front();
P.pop();
for (int i=0;i<4;i++)
{
G.x=F.x+t[i][0];
G.y=F.y+t[i][1];
if(!inmap(G.x, G.y)||maps[G.x][G.y]=='#') continue;
if(!Mark[G.x][G.y])
{
Mark[G.x][G.y]=1;
G.ans=F.ans+M[i];
if(G.x==ex&&G.y==ey)
{
F=G;
return true;
}
P.push(G);
}
}
}
return false;
} void bfs()//箱子bfs
{
int i;
queue<xhx> Q;
f.bx=begx; f.by = begy;
f.px=begsx; f.py = begsy;
f.ans="";
mark[begx][begy]=1;
Q.push(f);
while (!Q.empty())
{
f=Q.front();
Q.pop();
for (i=0;i<4;i++)
{
int newx=f.bx+t[i][0],newy=f.by+t[i][1];//箱子要到达的地方
int tx=f.bx-t[i][0],ty=f.by-t[i][1];//人要到达的地方
if (!inmap(newx, newy)||maps[newx][newy]=='#'||!inmap(tx, ty)||maps[tx][ty]=='#'||mark[newx][newy])
continue;
if (ren(f.px,f.py,tx,ty))
{
g.bx=newx; g.by=newy;
g.px=f.bx; g.py=f.by;
g.ans=f.ans+F.ans+P[i];
if(g.bx==endx&&g.by==endy)
{
cout<<g.ans<<endl<<endl;
return ;
}
mark[newx][newy]=1;
Q.push(g);
}
}
}
printf("Impossible.\n\n");
} int main()
{
int ci=1,i,j;
while(scanf("%d%d",&r,&c)&&(r + c))
{
memset(mark,0,sizeof(mark));
for (i=1;i<=r;++i)
scanf("%s",maps[i]+1);
for (i=1;i<=r;++i)
for (j=1;j<=c;++j)
{
if(maps[i][j]=='B') begx=i, begy=j;
if(maps[i][j]=='T') endx=i, endy=j;
if(maps[i][j]=='S') begsx=i, begsy=j;
}
printf("Maze #%d\n",ci++);
bfs();
}
return 0;
}