bfs求最短路,递归打印最短路的具体路径;
难点:
当前状态和转弯方式很复杂,要仔细处理;
递归打印:用一个数组存储路径中结点的前一个节点,递归查找 (bfs无法确定下一个结点,但对于没一个结点,它的上一个结点是确定的!)
ps:输出因为太懒不想处理所以按书上打的;递归打印理解有点麻烦。。。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstdio>
using namespace std; struct node {
int x,y;
int w;
void init (int nx,int ny,int nw){
x=nx;
y=ny;
w=nw;
}
}p[][][]; int visit[][][];
int map[][][];
int dir[][][]={{-,,,-,,},
{,,-,,,},
{,,,,,-},
{,-,,,-,}
}; int id (char c){
if (c=='N'||c=='F')
return ;
else if (c=='E'||c=='L')
return ;
else if (c=='S'||c=='R')
return ;
else return ;
}
node ans[];
int tot;
int x0,y0,x1,y1,w1,sx,sy; void print (int x,int y,int w); int bfs (int x,int y,int w){
queue<node> q;
while (!q.empty ())
q.pop ();
node a,b;
a.init (x,y,w);
visit[a.x][a.y][a.w]=;
q.push (a);
while (!q.empty ()){
a=q.front ();//cout<<a.x<<" "<<a.y<<" "<<a.w<<endl;
q.pop ();
if (a.x==sx&&a.y==sy){
print (a.x,a.y,a.w);
return ;
}
int xx,yy,ww;
for (int i=;i<;i++){
xx=a.x;yy=a.y;ww=a.w;
xx+=dir[a.w][i][];
yy+=dir[a.w][i][];
if (i==)
ww=(ww+)%;
else if (i==)
ww=(ww+)%;
b.init (xx,yy,ww);
if ((map[a.x][a.y][a.w]&(<<i))){
if (xx<||xx>||yy<||yy>)
continue ;
if (visit[xx][yy][ww]>=)
continue ;
visit[xx][yy][ww]=visit[a.x][a.y][a.w]+;
p[xx][yy][ww]=a; //存储路径中的父结点
q.push (b);
} }
}
return ;
} void print (int x,int y,int w){
vector<node> v;
node a,b;
a.init (x,y,w);
v.push_back (a);
while (visit[a.x][a.y][a.w]){
a=p[a.x][a.y][a.w];
v.push_back (a);
}
a.init (x0,y0,w1);
v.push_back (a); int cnt=;
for (int i=v.size()-;i>=;i--){
if (cnt%==) cout<<" ";
cout<<" ("<<v[i].x<<","<<v[i].y<<")";
if (++cnt%==) cout<<endl;
}
if (v.size()%!=) cout<<endl;
} int main (){
char s[];
while (cin>>s){
if (strcmp (s,"END")==)
break ;
tot=;
memset (map,,sizeof map);
memset (visit,-,sizeof visit);
cout<<s<<endl;
char c;
cin>>x1>>y1>>c>>sx>>sy;
x0=x1;y0=y1;
w1=id (c);
x1+=dir[w1][][];
y1+=dir[w1][][];
int xx,yy;
while (cin>>xx&&xx){
cin>>yy;
gets (s);
int i=;
int j=id (s[]);
while (s[i++]!='*'){//cout<<i<<" "<<s[i];
if (s[i]==' '){
j=id (s[++i]);
continue ;
}
map[xx][yy][j]^=(<<id (s[i]));
}
//for (j=0;j<4;j++)
// cout<<map[xx][yy][j]<<endl;
}//cout<<xx<<endl;
if (!bfs (x1,y1,w1))
cout<<" No Solution Possible"<<endl;
}
return ;
}