1. 程式人生 > >UVA 10047 The Monocycle(BFS)

UVA 10047 The Monocycle(BFS)

題意:從S走到T,每走一格車輪轉一個顏色,求到T時車輪顏色為綠色(起始也為綠色)的最短路徑。每次可向當前車輪方向走一格,或者原地向左轉動或向右轉動。

思路:幾乎也為裸的BFS,多記錄一些狀態,即需要記錄到某點車輪為某個方向某個顏色時的最短路徑。

程式碼:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>

using namespace std;

const
int N = 40; const int INF = 0x3f3f3f3f; struct Node { int x, y; int color, step, turn; }; char _map[N][N]; int n, m; int dis[N][N][10][10]; int x[4] = {-1, 0, 1, 0}; int y[4] = {0, 1, 0, -1}; bool pass(Node to) { if (to.x >= 0 && to.x < n && to.y >= 0 && to.y < m && _map[to
.x][to.y] != '#' && dis[to.x][to.y][to.color][to.turn] > to.step) return true; return false; } int bfs(Node s) { memset(dis, INF, sizeof(dis)); queue<Node> q; q.push(s); dis[s.x][s.y][s.color][s.turn] = s.step; while (!q.empty()) { Node now = q.front(); q.pop(); if
(_map[now.x][now.y] == 'T' && now.color == 0) { return now.step; } Node to; to.x = now.x; to.y = now.y; to.color = now.color; to.step = now.step + 1; to.turn = (now.turn + 1) % 4; if (pass(to)) { q.push(to); dis[to.x][to.y][to.color][to.turn] = to.step; } to.turn = (now.turn + 3) % 4; if (pass(to)) { q.push(to); dis[to.x][to.y][to.color][to.turn] = to.step; } to.x = now.x + x[now.turn]; to.y = now.y + y[now.turn]; to.color = (now.color + 1) % 5; to.turn = now.turn; if (pass(to)) { q.push(to); dis[to.x][to.y][to.color][to.turn] = to.step; } } return -1; } int main() { int i_case = 1; while (scanf("%d%d", &n, &m) != EOF) { if (!n && !m) break; for (int i = 0; i < n; i++) scanf("%s", _map[i]); Node st; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (_map[i][j] == 'S') { st.x = i, st.y = j; st.turn = 0; st.color = 0; st.step = 0; } } } int res = bfs(st); if (i_case > 1) printf("\n"); if (res == -1) printf("Case #%d\ndestination not reachable\n", i_case++); else printf("Case #%d\nminimum time = %d sec\n", i_case++, res); } return 0; }