题目大意:一张图,问从起点到终点的最短时间是多少。方向转动也消耗时间。
题目分析:图的广度优先遍历。。。
代码如下:
# include<iostream>
# include<cstdio>
# include<queue>
# include<cstring>
# include<algorithm>
using namespace std;
struct Node
{
int x,y,f,l,t;
Node(int _x,int _y,int _f,int _l,int _t):x(_x),y(_y),f(_f),l(_l),t(_t){}
bool operator < (const Node &a) const {
return t>a.t;
}
};
int d[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
int vis[30][30][4][5],n,m;
char p[30][30];
void bfs(int sx,int sy)
{
priority_queue<Node>q;
memset(vis,0,sizeof(vis));
vis[sx][sy][0][0]=1;
q.push(Node(sx,sy,0,0,0));
while(!q.empty())
{
Node u=q.top();
q.pop();
if(p[u.x][u.y]=='T'&&u.l==0){
printf("minimum time = %d sec\n",u.t);
return ;
}
if(!vis[u.x][u.y][(u.f+3)%4][u.l]){
vis[u.x][u.y][(u.f+3)%4][u.l]=1;
q.push(Node(u.x,u.y,(u.f+3)%4,u.l,u.t+1));
}
if(!vis[u.x][u.y][(u.f+1)%4][u.l]){
vis[u.x][u.y][(u.f+1)%4][u.l]=1;
q.push(Node(u.x,u.y,(u.f+1)%4,u.l,u.t+1));
}
int nx=u.x+d[u.f][0],ny=u.y+d[u.f][1];
if(nx<0||nx>=n||ny<0||ny>=m||p[nx][ny]=='#') continue;
if(!vis[nx][ny][u.f][(u.l+1)%5]){
vis[nx][ny][u.f][(u.l+1)%5]=1;
q.push(Node(nx,ny,u.f,(u.l+1)%5,u.t+1));
}
}
printf("destination not reachable\n");
}
int main()
{
int sx,sy,cas=0,flag=0;
while(scanf("%d%d",&n,&m)&&(n+m))
{
if(flag) printf("\n");
flag=1;
for(int i=0;i<n;++i){
scanf("%s",p[i]);
for(int j=0;j<m;++j)
if(p[i][j]=='S')
sx=i,sy=j;
}
printf("Case #%d\n",++cas);
bfs(sx,sy);
}
return 0;
}