#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
#define rep(i,n) for(int (i)=0;(i)<(n);i++)
#define Rep(i,n) for(int (i)=1;(i)<=(n);i++)
const int maxn = 90;
const int dx[] = {-1,0,1,0};
const int dy[] = {0,1,0,-1};
const char* str="NESW";
struct node{
int x,y,dir;
node(int x=0,int y=0,int dir=0):x(x),y(y),dir(dir){}
}S,E;
char ma[maxn][maxn];
int n,m,vis[maxn][maxn],fa[maxn*maxn];
node st[maxn*maxn];
vector<node> ans;
void print_ans(int f){
ans.clear();
while(f>0){
ans.push_back(st[f]);
f = fa[f];
}
for(int i=ans.size()-1;i>=0;i--){
printf("%c ",ans[i].dir);
int j,cnt=0;
for(j=i;j>=0;j--){
if(ans[i].dir!=ans[j].dir) break;
cnt++;
}
printf("%d\n",cnt);
i = j+1;
}
}
int bfs(){
int front_ = 0,rear=1;
st[0] = S;
memset(vis,-1,sizeof(vis));
vis[S.x][S.y] = 0;
while(front_<rear){
node u = st[front_];
if(u.x==E.x&&u.y==E.y){
print_ans(front_);
return 1;
}
for(int i=0;i<4;i++){
int nr=u.x+dx[i],nl=u.y+dy[i];
int nx=u.x+dx[i]*2,ny=u.y+dy[i]*2;
if(nx>=0&&nx<=n&&ny>=0&&ny<=m&&(ma[nx][ny]=='+'||ma[nx][ny]=='E')&&vis[nx][ny]==-1&&(ma[nr][nl]=='-'||ma[nr][nl]=='|' )){
vis[nx][ny] = vis[u.x][u.y]+1;
fa[rear] = front_;
st[rear++]=node(nx,ny,str[i]);
}
}
front_++;
}
return 0;
}
int main()
{
while(scanf("%d %d",&n,&m)==2){
n=n*2-1; m=m*2-1;
Rep(i,n) {
scanf("%s",ma[i]+1);
Rep(j,m){
if(ma[i][j]=='S'){S=node(i,j);}
if(ma[i][j]=='E'){E=node(i,j);}
}
}
bfs();
}
return 0;
}
POJ 2435(打印最优解方案)
最新推荐文章于 2019-03-28 22:54:37 发布