原题链接:https://vjudge.net/problem/UVA-10047
绞尽脑汁的图论题,虽然只是bfs但是要求到达的最小时间以及符合到达终点的条件还是需要思考一番。
用优先队列保证到达时间最小,每一个方块的访问方式由进入的方向以及轮子的颜色划分。
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
int n,m;
int sx,sy,ex,ey;
char G[30][30];
bool judge[30][30][4][5];
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
typedef pair<int,int> P;
struct node
{
int x,y;
int d,c;
int t;
vector<P> v;
friend bool operator<(node a,node b){
return a.t>b.t;
}
};
int bfs()
{
node p;
bool flag=0;
p.x=sx;
p.y=sy;
p.d=0;
p.c=0;
p.t=0;
p.v.push_back(P(sx,sy));
memset(judge,true,sizeof(judge));
judge[sx][sy][0][0]=false;
priority_queue<node> que;
que.push(p);
//printf("x y d c t\n");
while(!que.empty())
{
p=que.top();
//printf("%d %d %d %d %d\n",p.x,p.y,p.d,p.c,p.t);
que.pop();
if(p.x==ex&&p.y==ey&&p.c==0)
{
flag=1;
break;
}
for(int i=0;i<4;i++)
{
node np;
if(p.d==i)
{
int nx=p.x+dx[i];
int ny=p.y+dy[i];
int c=p.c+1;
if(c==5)
c=0;
if(nx>=0&&nx<n&&ny>=0&&ny<m&&G[nx][ny]=='.'&&judge[nx][ny][i][c])
{
np.x=nx;
np.y=ny;
np.c=c;
np.t=p.t+1;
np.d=i;
judge[nx][ny][i][c]=false;
for(int j=0;j<p.v.size();j++)
np.v.push_back(P(p.v[j].first,p.v[j].second));
np.v.push_back(P(nx,ny));
que.push(np);
}
}
else
{
np.t=p.t;
if(abs(i-p.d)==1||abs(i-p.d)==3)
np.t+=1;
if(abs(i-p.d)==2)
np.t+=2;
np.x=p.x;
np.y=p.y;
np.d=i;
np.c=p.c;
if(judge[p.x][p.y][i][p.c])
{
judge[p.x][p.y][i][p.c]=false;
for(int j=0;j<p.v.size();j++)
np.v.push_back(P(p.v[j].first,p.v[j].second));
que.push(np);
}
}
}
}
if(flag)
{
// for(int i=0;i<p.v.size();i++)
// printf("%d %d\n",p.v[i].first,p.v[i].second);
return p.t;
}
else
return -1;
}
int main()
{
int cas=1;
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0&&m==0)
break;
for(int i=0;i<n;i++)
{
getchar();
for(int j=0;j<m;j++)
{
scanf("%c",&G[i][j]);
if(G[i][j]=='S')
{
sx=i;
sy=j;
G[i][j]='.';
}
if(G[i][j]=='T')
{
ex=i;
ey=j;
G[i][j]='.';
}
}
}
int ans=bfs();
if(cas>1)
printf("\n");
printf("Case #%d\n",cas++);
if(ans!=-1)
printf("minimum time = %d sec\n",ans);
else
printf("destination not reachable\n");
}
return 0;
}