您的位置:首页 > 其它

UVA 816 Abbott’s Revenge

2014-07-19 14:19 281 查看
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[10][10][5];

int visit[10][10][5];
int map[10][10][4];
int dir[4][3][2]={{-1,0,0,-1,0,1},
{0,1,-1,0,1,0},
{1,0,0,1,0,-1},
{0,-1,1,0,-1,0}
};

int id (char c){
if (c=='N'||c=='F')
return 0;
else if (c=='E'||c=='L')
return 1;
else if (c=='S'||c=='R')
return 2;
else return 3;
}
node ans[1000];
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]=0;
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 1;
}
int xx,yy,ww;
for (int i=0;i<3;i++){
xx=a.x;yy=a.y;ww=a.w;
xx+=dir[a.w][i][0];
yy+=dir[a.w][i][1];
if (i==1)
ww=(ww+3)%4;
else if (i==2)
ww=(ww+1)%4;
b.init (xx,yy,ww);
if ((map[a.x][a.y][a.w]&(1<<i))){
if (xx<1||xx>9||yy<1||yy>9)
continue ;
if (visit[xx][yy][ww]>=0)
continue ;
visit[xx][yy][ww]=visit[a.x][a.y][a.w]+1;
p[xx][yy][ww]=a;    //存储路径中的父结点
q.push (b);
}

}
}
return 0;
}

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=0;
for (int i=v.size()-1;i>=0;i--){
if (cnt%10==0) cout<<" ";
cout<<" ("<<v[i].x<<","<<v[i].y<<")";
if (++cnt%10==0) cout<<endl;
}
if (v.size()%10!=0) cout<<endl;
}

int main (){
char s[30];
while (cin>>s){
if (strcmp (s,"END")==0)
break ;
tot=0;
memset (map,0,sizeof map);
memset (visit,-1,sizeof visit);
cout<<s<<endl;
char c;
cin>>x1>>y1>>c>>sx>>sy;
x0=x1;y0=y1;
w1=id (c);
x1+=dir[w1][0][0];
y1+=dir[w1][0][1];
int xx,yy;
while (cin>>xx&&xx){
cin>>yy;
gets (s);
int i=1;
int j=id (s[1]);
while (s[i++]!='*'){//cout<<i<<" "<<s[i];
if (s[i]==' '){
j=id (s[++i]);
continue ;
}
map[xx][yy][j]^=(1<<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 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: