#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include<cmath>
#include<map>
#include<set>
using namespace std;
int dic[4][2]={{-1,0},{0,-1},{1,0},{0,1}};
const int INF=1000000000;
const int maxm=25+10;
const int maxn=25+10;
int m,n;
char maze[maxm][maxn];
struct State
{
int x,y,dir,color;
State(int x=0,int y=0,int dir=0,int color=0):x(x),y(y),dir(dir),color(color){}
};
int vis[maxm][maxn][4][5];
int d[maxm][maxn][4][5];
queue<State> que;
int sx,sy;
int tx,ty;
int ans;
void update(int x,int y,int dir,int color,int v)
{
if(x<0||x>=m||y<0||y>=n)return ;
if(maze[x][y]=='.'&&!vis[x][y][dir][color])
{
vis[x][y][dir][color]=1;
d[x][y][dir][color]=v;
que.push(State(x,y,dir,color));
if(x==tx&&y==ty&&color==0)ans=min(ans,d[x][y][dir][color]);
}
}
void bfs(State st)
{
vis[st.x][st.y][st.dir][st.color]=1;
d[st.x][st.y][st.dir][st.color]=0;
que.push(st);
while(!que.empty())
{
State p=que.front();
que.pop();
int v=d[p.x][p.y][p.dir][p.color]+1;
update(p.x,p.y,(p.dir+1)%4,p.color,v);
update(p.x,p.y,(p.dir+3)%4,p.color,v);
update(p.x+dic[p.dir][0],p.y+dic[p.dir][1],p.dir,(p.color+1)%5,v);
}
}
int main()
{
int num=1;
int kase=0;
while(~scanf("%d %d",&m,&n))
{
getchar();
if(m==0&&n==0)break;
for(int i=0;i<m;i++)
{
scanf("%s",maze[i]);
for(int j=0;j<n;j++)
{
if(maze[i][j]=='S')
{
sx=i;
sy=j;
}
if(maze[i][j]=='T')
{
tx=i;
ty=j;
}
}
}
memset(vis,0,sizeof(vis));
ans=INF;
maze[sx][sy]=maze[tx][ty]='.';
bfs(State(sx,sy,0,0));
if(num!=1)printf("\n");
printf("Case #%d\n",num++);
if(ans==INF)printf("destination not reachable\n");
else printf("minimum time = %d sec\n",ans);
}
return 0;
}
UVa10047 The Monocycle (BFS)
最新推荐文章于 2024-11-13 21:45:50 发布