The Monocycle

来源:互联网 发布:阿里云香港b区 编辑:程序博客网 时间:2024/03/29 14:36


The Monocycle

大意:

有一辆独轮车在广场上运动,开始时方向朝北,轮子接触地面的颜色为绿色,车子每向前走一格耗时1秒,拐弯耗时1秒;

车子轮胎由5种颜色组成;

求出一条耗时最短的路线,到达终点时,使得车子接触地面的也为绿色,方向无所谓;

要点:

判断车子是否可以走的标记数组应由传统的vis[x][y]转变成vis[x][y][dir][col],即判断坐标时也要考虑颜色与方向;

每次车子由3个选择向前走, 左拐,右拐;

代码:

#include <cstdio>#include <queue>#include <string.h>using namespace std;char map[30][30];char vis[30][30][4][5];   // 北0东1南2西3   green0, black1, red2, blue3, white4int m, n, sec;int d[4][2] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };struct node{int x, y;int dir, col;int s;node(int i1, int i2, int i3, int i4, int i5) :x(i1), y(i2), dir(i3), col(i4), s(i5){}};int bfs(){queue <struct node> que;for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if (map[i][j] == 'S'){que.push(node(i, j, 0, 0, 0));vis[i][j][0][0] = 1;break;}while (!que.empty()){node t = que.front();que.pop();if (map[t.x][t.y] == 'T' && t.col == 0)return t.s;int x = t.x + d[t.dir][0];int y = t.y + d[t.dir][1];if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y][t.dir][(t.col + 1) % 5] && map[x][y] != '#'){que.push(node(x, y, t.dir, (t.col + 1) % 5, t.s + 1));vis[x][y][t.dir][(t.col + 1) % 5] = 1;}if (!vis[t.x][t.y][(t.dir + 1) % 4][t.col]){que.push(node(t.x, t.y, (t.dir + 1) % 4, t.col, t.s + 1));vis[t.x][t.y][(t.dir + 1) % 4][t.col] = 1;}if (!vis[t.x][t.y][(t.dir - 1 == -1) ? 3 : t.dir - 1][t.col]){que.push(node(t.x, t.y, (t.dir - 1 == -1) ? 3 : t.dir - 1, t.col, t.s + 1));vis[t.x][t.y][(t.dir - 1 == -1) ? 3 : t.dir - 1][t.col] = 1;}}return 0;}int main(){int b = 0;while (scanf("%d%d", &m, &n) && m != 0){memset(vis, 0, sizeof(vis));memset(map, 0, sizeof(map));for (int i = 0; i < m; i++)scanf("%s", map[i]);sec = bfs();if (b)printf("\n");if (sec)printf("Case #%d\nminimum time = %d sec\n", ++b, sec);elseprintf("Case #%d\ndestination not reachable\n", ++b);}}



0 0