UVA 10047 - The Monocycle

来源:互联网 发布:python 元组转list 编辑:程序博客网 时间:2024/04/29 05:29

/* 四维的BFS  

*/

#include<cstdio>

#include<cstring>
#include<queue>
#include<cstdlib>
using namespace std;
int n,m,flag;
int d[5][5]= {{-1,0},{0,1},{1,0},{0,-1}};
char map[30][30];
int vis[30][30][30][30];
struct node
{
    int x,y;
    int d,f,c;
    bool operator < (const node &n) const
    {
        return d > n.d;
    }
};
int bfs(int x,int y,int f)
{
    priority_queue<node> q;
    node t;
    t.x=x;
    t.y=y;
    t.d=0;
    t.f=f;
    t.c=0;
    q.push(t);
    vis[x][y][0][0]=1;
    while(!q.empty())
    {
        node p = q.top(),s=p;
        q.pop();
        //int a[10]= {p.f,(p.f+1)%4,(p.f+3)%4,(p.f+2)%4};
        for(int i = 0; i < 4; i++)
        {
            s=p;
            if(i==p.f)
            {
                s.x=p.x+d[i][0];
                s.y=p.y+d[i][1];
                s.f=p.f;
                s.c=(p.c+1)%5;
                s.d=p.d+1;
            }
            else
            {
                s.f=i;
                s.x=p.x;
                s.y=p.y;
                s.c=p.c;
                if(abs(i-p.f)==2)
                    s.d=p.d+2;
                else s.d=p.d+1;
            }
            if(s.x>=0&&s.x<n&&s.y>=0&&s.y<m)
            {
                if(!vis[s.x][s.y][s.f][s.c]&&map[s.x][s.y]!='#')
                {
                    //printf("%d %d....%d %d ...%d\n",s.x,s.y,s.f,s.c,s.d);
                    if(map[s.x][s.y]=='T'&&s.c==0)
                    {
                        flag=1;
                        return s.d;
                    }
                    vis[s.x][s.y][s.f][s.c]=1;
                    q.push(s);
                }
            }
        }
    }
    return -1;
}
int main()
{
    int x,y;
    int count=0;
    while(1)
    {
        memset(vis,0,sizeof(vis));
        scanf("%d%d",&n,&m);
        if(!n&&!m) break;
        getchar();
        for(int i = 0; i < n; i++)
        {
            scanf("%s",map[i]);
            for(int j = 0; j < strlen(map[i]); j++)
                if(map[i][j]=='S')
                {
                    x = i;
                    y = j;
                    break;
                }
        }
        flag=0;
        int dd=bfs(x,y,0);
        if(count>0) printf("\n");
        printf("Case #%d\n",++count);
        if(!flag)
            printf("destination not reachable\n");
        else
            printf("minimum time = %d sec\n",dd);


    }
    return 0;
}
原创粉丝点击