UVA 10047 - The Monocycle

题目大意:走迷宫从S走到T,初始时,车头向北(四个方向),车轮为绿色(五种颜色),每次只可以左右转,转一次一秒,行进一步一秒。每走一步,轮子变色。要求到达T最短时间且轮子为绿色。

解题思路:用四维标记数组代表位置,颜色,方向。bfs求解。队列每次一种状态,每次将左右转状态转入队。每次前进方向与车头方向一致。

ac代码:

#include <iostream>
#include <cstring> 
#include <queue>
using namespace std;
int n, m, vis[30][30][5][4];
int ex[2], goal[2], temp, cnt=1;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
char map[30][30];
struct node{
	int x;
	int y;
	int dir;
	int col;
};
queue <node>qu;
int bfs()
{
	int t1, t2, t3, t4, sum=0;
	while (!qu.empty())
		qu.pop();
	node temp;
	temp.x = ex[0], temp.y = ex[1];
	temp.col = 0, temp.dir = 0;
	vis[ex[0]][ex[1]][0][0] = 0;
	qu.push(temp);
	while (!qu.empty()){
		temp = qu.front();
		qu.pop();
		t1 = temp.x, t2 = temp.y;
		t3 = temp.col, t4 = temp.dir;
		if (t1 == goal[0] && t2 == goal[1] && !t3)
				return vis[t1][t2][t3][t4];
		node no = temp;
		for (int i=0; i<4; i++){
			if (i == 2 || vis[t1][t2][t3][(t4+i)%4] != -1)
				continue;
			vis[t1][t2][t3][(t4+i)%4] = vis[t1][t2][t3][t4] + 1;
			no.dir = (t4+i)%4;
			qu.push(no);
		}
		if (t1+dx[t4] >= 0 && t1+dx[t4] < n &&
		t2+dy[t4] >= 0 && t2+dy[t4] <m && 
		map[t1+dx[t4]][t2+dy[t4]] != '#' &&
		vis[t1+dx[t4]][t2+dy[t4]][(t3+1)%5][t4] == -1){
			vis[t1+dx[t4]][t2+dy[t4]][(t3+1)%5][t4] = vis[t1][t2][t3][t4] + 1;
			no.x = t1+dx[t4], no.y = t2+dy[t4];
			no.col = (t3+1)%5, no.dir = t4;
			qu.push(no);
		}
	}
return 0;
}
int main()
{
	while (scanf("%d%d", &n, &m)!=EOF){
		if (!n && !m)
			break;
		if (cnt != 1)
			printf("\n");
		memset(vis, -1, sizeof(vis));
		for (int i=0; i<n; i++){
			scanf("%s", map[i]);
			for (int j=0; j<m; j++)
				if (map[i][j] == 'S')
					ex[0] = i, ex[1] = j;
				else if (map[i][j] == 'T')
					goal[0] = i, goal[1] = j;
		}
		temp = bfs();
		printf("Case #%d\n", cnt++);
		if (temp)
			printf("minimum time = %d sec\n", temp);
		else
			printf("destination not reachable\n");
	}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值