uva816 Abbott's Revenge(bfs 模拟代码题)

锻炼打代码的能力....

#include<bits/stdc++.h>
const int inf=0x7fffffff;
using namespace std;
struct Node{
  int x,y,dir;
};
int dir;
int has_edge[10][10][5][4],d[10][10][5],r0,r1,r2,c0,c1,c2;
Node p[10][10][5];
const char* dirs="NESW";
const char* turns="FLR";
int dir_id(char c){return strchr(dirs,c)-dirs;}
int turn_id(char c){return strchr(turns,c)-turns;}
const int nxt[4][2]={-1,0,0,1,1,0,0,-1};
Node walk(const Node &u,int turn)
{
     int dir=u.dir;
     if(turn==1) dir=(dir+3)%4;
     if(turn==2) dir=(dir+1)%4;
     return Node{u.x+nxt[dir][0],u.y+nxt[dir][1],dir};
}

bool inside(int x,int y){
  return (x>=1&&y>=1&&x<=9&&y<=9);
}

void print(Node u)
{
   vector<Node> nodes;
   while(1){
     nodes.push_back(u);
     if((d[u.x][u.y][u.dir]==0)) break;
     u=p[u.x][u.y][u.dir];
   }
   nodes.push_back(Node{r0,c0,dir});
   int cnt=0;
   for(int i=nodes.size()-1;i>=0;i--){
       cnt++;
       if(cnt%10==1) printf("  (%d,%d)",nodes[i].x,nodes[i].y);
       else if(cnt%10>=2) printf(" (%d,%d)",nodes[i].x,nodes[i].y);
       else if(cnt%10==0) printf(" (%d,%d)\n",nodes[i].x,nodes[i].y);
   }
   if(nodes.size()%10!=0) printf("\n");
}

void solve()
{
   queue<Node> q;
   memset(d,-1,sizeof(d));
   q.push(Node{r1,c1,dir});
   d[r1][c1][dir]=0;
   while(!q.empty()){
     Node now=q.front();q.pop();
     if(now.x==r2&&now.y==c2){
        print(now);
        return;
     }
     for(int i=0;i<4;i++){
        Node v=walk(now,i);
        if(has_edge[now.x][now.y][now.dir][i]&&inside(v.x,v.y)&&d[v.x][v.y][v.dir]<0){
            d[v.x][v.y][v.dir]=d[now.x][now.y][now.dir]+1;
            p[v.x][v.y][v.dir]=now;
            q.push(v);
        }
     }
   }
   printf("  No Solution Possible\n");
}

int main()
{
    char s[20];
    while(scanf("%s",s)&&strcmp(s,"END")){
        memset(has_edge,0,sizeof(has_edge));
        char ch;
        scanf("%d %d %c %d %d",&r0,&c0,&ch,&r2,&c2);
        dir=dir_id(ch);
        r1=r0+nxt[dir][0];c1=c0+nxt[dir][1];
        int x,y; string str;
        while(cin>>x&&x){
            cin>>y;
            while(cin>>str&&str[0]!='*'){
                for(int i=1;i<str.size();i++){
                    has_edge[x][y][dir_id(str[0])][turn_id(str[i])]=1;
                }
            }
        }
        printf("%s\n",s);
        solve();
    }
}


你可能感兴趣的:(uva816 Abbott's Revenge(bfs 模拟代码题))