题目大意:给你一个地图,给你一个车轮,车轮上有五种颜色,刚开始车轮朝向北,就是上,绿色在地面上。要求从开始位置到达结束位置车轮的绿色颜色在地面上,有三个执行命令。
第一:方向不变,向前移动到下一个方块;
第二:在当前方块中向左转90°;
第三:在当前方块中向右转90°;
题解:先定义一个方向,上、右、下、左顺时针方向,有四种状态,x、y,所在的位置,以及d,此时朝向的方向,c此时车轮在地面上的颜色。
需要注意的是book标记数组不要开的太大,会超时,注意不要用next,会显示格式错误。
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
char mp[35][35];
int book[35][35][4][5];
int to[4][2]= {-1,0,0,1,1,0,0,-1};
int m,n;
int sx,sy,ex,ey;
struct note
{
int x,y,d,c,time;
} t,head,tnext;
queue<note> q;
int bfs()
{
t.x=sx,t.y=sy,t.d=0,t.c=0,t.time=0;
book[sx][sy][0][0]=1;
q.push(t);
while(!q.empty())
{
head=q.front();
if(head.x==ex&&head.y==ey&&head.c==0)
return head.time;
q.pop();
tnext.x=head.x;
tnext.y=head.y;
tnext.c=head.c;
tnext.d=(head.d+1)%4;
tnext.time=head.time+1;
if(book[tnext.x][tnext.y][tnext.d][tnext.c]==0)
{
book[tnext.x][tnext.y][tnext.d][tnext.c]=1;
q.push(tnext);
}
tnext.x=head.x;
tnext.y=head.y;
tnext.c=head.c;
tnext.d=(head.d+3)%4;
tnext.time=head.time+1;
if(book[tnext.x][tnext.y][tnext.d][tnext.c]==0)
{
book[tnext.x][tnext.y][tnext.d][tnext.c]=1;
q.push(tnext);
}
tnext.x=head.x+to[head.d][0];
tnext.y=head.y+to[head.d][1];
tnext.c=(head.c+1)%5;
tnext.d=head.d;
tnext.time=head.time+1;
if(mp[tnext.x][tnext.y]=='#')
continue;
if(book[tnext.x][tnext.y][tnext.d][tnext.c]==1)
continue;
if(tnext.x<0||tnext.x>=m||tnext.y<0||tnext.y>=n)
continue;
book[tnext.x][tnext.y][tnext.d][tnext.c]=1;
q.push(tnext);
}
return 0;
}
int main()
{
int ans=0;
while(~scanf("%d%d",&m,&n)&&m&&n)
{
ans++;
while(!q.empty())
q.pop();
memset(book,0,sizeof(book));
int i,j,k;
for(i=0; i<m; i++)
scanf("%s",mp[i]);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
if(mp[i][j]=='S')
sx=i,sy=j;
if(mp[i][j]=='T')
ex=i,ey=j;
}
}
int minn=bfs();
if(ans>1)
printf("\n");
if(minn)
printf("Case #%d\nminimum time = %d sec\n",ans,minn);
else
printf("Case #%d\ndestination not reachable\n",ans);
}
return 0;
}