UVA 10047(p308)----The Monocycle

#include<bits/stdc++.h>
#define debu
using namespace std;
const int INF=999999;
const int dx[4]={0,1,0,-1};
const int dy[4]={1,0,-1,0};
string st[30];
int vis[30][30][4][5];
struct point
{
    int x,y,dir,col,s;
    point(int a=0,int b=0,int c=0,int d=0,int e=0):x(a),y(b),dir(c),col(d),s(e) {}
};
queue<point> q;
int n,m,stx,sty,enx,eny,ans;
int check(point a)
{
    return a.x==enx&&a.y==eny&&a.col==2;
}
int can(point a)
{
    return a.x<n&&a.x>=0&&a.y<m&&a.y>=0&&!vis[a.x][a.y][a.dir][a.col]&&st[a.x][a.y]!='#';
}
point make(int flag,point u)
{
    point v=u;
    if(flag==0)
    {
        v.x=u.x+dx[u.dir];
        v.y=u.y+dy[u.dir];
        v.col=(u.col+1)%5;
    }
    if(flag==1)
        v.dir=(u.dir+1)%4;
    if(flag==2)
        v.dir=(u.dir+3)%4;
    return v;
}
void solve()
{
    memset(vis,0,sizeof(vis));
    while(!q.empty()) q.pop();
    q.push(point(stx,sty,3,2,0));
    vis[stx][sty][3][2]=1;
    while(!q.empty())
    {
        point u=q.front();
        q.pop();
        for(int i=0; i<3; i++)
        {
            point v=make(i,u);
            if(can(v))
            {
                v.s=u.s+1;
              // cout<<u.x<<" "<<u.y<<" "<<u.dir<<" "<<v.x<<" "<<v.y<<" "<<v.dir<<" "<<v.s<<endl;
                if(check(v))
                {
                    ans=v.s;
                    return ;
                }
                vis[v.x][v.y][v.dir][v.col]=1;
                q.push(v);
            }
        }
    }
}
void input()
{
    for(int i=0; i<n; i++)
    {
        cin>>st[i];
        for(int j=0; j<m; j++)
        {
            if(st[i][j]=='S')
            {
                stx=i;
                sty=j;
            }
            if(st[i][j]=='T')
            {
                enx=i;
                eny=j;
            }
        }
    }
}
int main()
{
#ifdef debug
    freopen("in.in","r",stdin);
#endif // debug
    int cas=0;
    while(scanf("%d%d",&n,&m)==2&&n)
    {
        if(cas!=0) printf("\n");
         printf("Case #%d\n",++cas);
        ans=INF;
        input();
        solve();
        if(ans!=INF) printf("minimum time = %d sec\n",ans);
        else printf("destination not reachable\n");
    }
    return 0;
}

题目地址:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=988

题解:(x,y,dir,col)作为一个状态,BFS。

你可能感兴趣的:(UVA 10047(p308)----The Monocycle)