The Monocycle(bfs+四维标记状态)

题目提交:https://vjudge.net/problem/UVA-10047

题目大意:给你一个地图,给你一个车轮,车轮上有五种颜色,刚开始车轮朝向北,就是上,绿色在地面上。要求从开始位置到达结束位置车轮的绿色颜色在地面上,有三个执行命令。

第一:方向不变,向前移动到下一个方块;

第二:在当前方块中向左转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;
//0,1,2,3 上、右、下、左
//0,1,2,3,4 //0表示绿色,我们只用到绿色
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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值