当前位置: 代码迷 >> 综合 >> POJ 1475 Pushing Boxes 嵌套BFS -
  详细解决方案

POJ 1475 Pushing Boxes 嵌套BFS -

热度:88   发布时间:2023-09-23 07:29:41.0

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

题意Push路程要最少,所以直接找box到T的最短路径

box能动的前提是有个man能直接在他后面推他

所以再加一个BFS找man到他后面的最短路径

然后思考要优选队列里要保存哪些信息

box在何处 这个肯定要

还要保存路径啊,题目求的就是这个,所以box从起点到该点路径要保存,那么直接放个Path字符串保存一下路径就好了

然后要求man到box屁股后面的路径,那必须要知道man原来在哪里对不对,所以再保存个man点


算法就是BFS box走一步时再BFS man看看能不能走


AC代码如下:

#include<cstdio>
#include<cstring>
#include<queue> 
#include<string> 
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn=20+5;
int R,C;
char G[maxn][maxn];
struct Point{int x,y;Point(int x=0,int y=0):x(x),y(y){} bool operator == (const Point& p){return x==p.x&&y==p.y;}bool operator != (const Point& p){return !(*this==p);}
}box,terminal,start;
struct Node{Point box;Point man;string path; //man保存此box时man的位置 Node(Point b,Point man,string p):box(b),man(man),path(p){}Node(Point man,string p):man(man),path(p){}
};
const int dx[]={-1,1,0,0};
const int dy[]={0,0,-1,1};
const char d[]="NSWEnswe";
void Print(Point p){cout<<p.x<<' '<<p.y<<endl;
}
Point move(Point p,int i){return Point(p.x+dx[i],p.y+dy[i]);
}
bool inside(Point p){return p.x>=1&&p.x<=R&&p.y>=1&&p.y<=C;
}
string BFS_MAN(Point s,Point t,Point box) //s->t 中间不能经过box 
{queue<Node> Q;bool vis[maxn][maxn]={false};Q.push(Node(s,""));while(!Q.empty()){Point u=Q.front().man; string path=Q.front().path; Q.pop();if(u==t) return path;for(int i=0;i<4;i++){Point v=move(u,i);if(!inside(v)||G[v.x][v.y]=='#'||box==v||vis[v.x][v.y]) continue;vis[v.x][v.y]=true;Q.push(Node(v,path+d[i+4]));}}return "";
}bool BFS_BOX()
{queue<Node> Q;bool vis[maxn][maxn][4]={false};Q.push(Node(box,start,"")); while(!Q.empty()){Point ubox=Q.front().box,uman=Q.front().man; string path=Q.front().path; Q.pop();if(ubox==terminal) {cout<<path<<endl;return true;}for(int i=0;i<4;i++){Point vbox=move(ubox,i);if(!inside(vbox)||G[vbox.x][vbox.y]=='#'||vis[vbox.x][vbox.y][i]) continue;Point vman=move(ubox,i^1);  //反方向走 if(!inside(vman)||G[vman.x][vman.y]=='#') continue;string ManPath;if(vman!=uman){ManPath=BFS_MAN(uman,vman,ubox);if(ManPath.empty()) continue;}vis[vbox.x][vbox.y][i]=true;Q.push(Node(vbox,ubox,path+ManPath+d[i]));}}return false;
}
int main()
{int kase=0;while(cin>>R>>C){if(R==0&&C==0) break;for(int i=1;i<=R;i++) {cin>>(G[i]+1);for(int j=1;j<=C;j++)if(G[i][j]=='T') terminal=Point(i,j);else if(G[i][j]=='B') box=Point(i,j);else if(G[i][j]=='S') start=Point(i,j);}printf("Maze #%d\n",++kase);if(!BFS_BOX()) cout<<"Impossible."<<endl; 		cout<<endl; }return 0;
}







  相关解决方案