Abbott's Revenge UVA - 816(带方向bfs)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/leekerian/article/details/86759701
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>


using namespace std;

const int MAXN=11;
struct node{
    int r,c,dir;
    node(){}
    node(int _r,int _c,int _dir){r=_r,c=_c,dir=_dir;}
};

int r0,c0,r2,c2;

const char* Dir="NESW";
const char* Turn="FLR";

int t_dir(char t)
{
    return strchr(Dir,t)-Dir;
}

int t_trun(char t)
{
    return strchr(Turn,t)-Turn;
}


int mx[4]={-1,0,1,0};
int my[4]={0,1,0,-1};
node st;
int has_edg[MAXN][MAXN][5][5];
node f[MAXN][MAXN][5];
int d[MAXN][MAXN][5];
bool read()
{
    char str[111],str1[111];
    if(scanf("%s%d%d%s%d%d",str,&r0,&c0,str1,&r2,&c2)!=6)
        return false;
    printf("%s\n",str);
    int dir1=t_dir(str1[0]);
    st.r=r0+mx[dir1],st.c=c0+my[dir1],st.dir=dir1;
    memset(has_edg,0,sizeof(has_edg));
    while(1)
    {
        int a,b;
        scanf("%d",&a);
        if(a==0)
            break;
        scanf("%d",&b);
        char str2[111];
        while(scanf("%s",str2)==1)
        {
            if(str2[0]=='*') break;
            for(int i=1;i<strlen(str2);i++)
                has_edg[a][b][t_dir(str2[0])][t_trun(str2[i])]=1;
        }
    }
    return true;
}

node walk(node& t,int i)
{
    int dir=t.dir;
    if(i==1) dir=(dir-1+4)%4;
    if(i==2) dir=(dir+1)%4;
    return node(t.r+mx[dir],t.c+my[dir],dir);
}

void pf(node& t)
{
    vector<node> vt;
    vt.push_back(t);
    while(1)
    {
        if(t.r==st.r&&t.c==st.c&&t.dir==st.dir)
        {
            vt.push_back(node(r0,c0,0));
            break;
        }
        t=f[t.r][t.c][t.dir];
        vt.push_back(t);
    }
    int cnt = 0;
    for(int i = vt.size()-1; i >= 0; i--) {
    if(cnt % 10 == 0) printf(" ");
    printf(" (%d,%d)", vt[i].r, vt[i].c);
    if(++cnt % 10 == 0) printf("\n");
  }
  if(vt.size() % 10 != 0) printf("\n");
}
void BFS()
{
    queue<node> qq;
    qq.push(st);
    memset(d,0,sizeof(d));
    d[st.r][st.c][st.dir]=1;
    f[st.r][st.c][st.dir]=st;
    while(!qq.empty())
    {
        node t=qq.front();
        if(t.r==r2&&t.c==c2) {pf(t);return;}
        qq.pop();
        for(int i=0;i<3;i++)
        {
            node v=walk(t,i);
            if(has_edg[t.r][t.c][t.dir][i]&&v.r>=1&&v.r<=9&&v.c>=1&&v.c<=9&&!d[v.r][v.c][v.dir])
            {
                d[v.r][v.c][v.dir]=1;
                f[v.r][v.c][v.dir]=t;
                qq.push(v);
            }
        }
    }
    printf("  No Solution Possible\n");
}
int main()
{
    while(read())
    {
        BFS();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/leekerian/article/details/86759701