UVa:10047 The Monocycle

简单bfs。

将状态映射成hash来判重。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#define ll long long
#define INF 200000000
#define MOD 20071027
#define MAXN 1000005
using namespace std;
int N,M;
char grid[30][30];
int move[4][2]= {{-1,0},{0,1},{1,0},{0,-1}};
struct Point
{
    int x,y,time,f,col;
    Point(int a=0,int b=0,int c=0,int d=0,int e=0):x(a),y(b),time(c),f(d),col(e) {}
};
bool vis[30][30][4][5];
bool Judge(int x,int y)
{
    if(x<1||y<1||x>M||y>N) return false;
    return true;
}
int bfs(int sx,int sy,int ex,int ey)
{
    queue<Point> que;
    que.push(Point(sx,sy,0,0,0));
    memset(vis,0,sizeof(vis));
    vis[sx][sy][0][0]=true;
    while(!que.empty())
    {
        Point p=que.front();
        que.pop();
        if(p.x==ex&&p.y==ey&&p.col==0) return p.time;
        int nx=p.x+move[p.f][0],ny=p.y+move[p.f][1],t=p.time+1,c=(p.col+1)%5;
        if(Judge(nx,ny)&&grid[nx][ny]!='#'&&!vis[nx][ny][p.f][c])
        {
            vis[nx][ny][p.f][c]=true;
            que.push(Point(nx,ny,t,p.f,c));
        }
        if(!vis[p.x][p.y][(p.f+1)%4][p.col])
        {
            vis[p.x][p.y][(p.f+1)%4][p.col]=true;
            que.push(Point(p.x,p.y,t,(p.f+1)%4,p.col));
        }

        if(!vis[p.x][p.y][(p.f-1+4)%4][p.col])
        {
            vis[p.x][p.y][(p.f-1+4)%4][p.col]=true;
            que.push(Point(p.x,p.y,t,(p.f-1+4)%4,p.col));
        }
    }
    return -1;
}
int main()
{
    int kase=0;
    while(scanf("%d%d",&M,&N))
    {
        if(!M&&!N) break;
        int sx,sy,ex,ey;
        if(kase) printf("\n");
        for(int i=1; i<=M; ++i)
        {
            scanf("%s",grid[i]+1);
            for(int j=1; grid[i][j]; ++j)
                if(grid[i][j]=='S')
                {
                    sx=i;
                    sy=j;
                }
                else  if(grid[i][j]=='T')
                {
                    ex=i;
                    ey=j;
                }
        }
        int ans=bfs(sx,sy,ex,ey);
        printf("Case #%d\n",++kase);
        if(ans==-1) puts("destination not reachable");
        else printf("minimum time = %d sec\n",ans);
    }
    return 0;
}


 

你可能感兴趣的:(bfs)