独轮车(The Monocycle, UVa 10047)
白书5.1 例题2
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
using namespace std;
const int N = 30;
int m, n;
char mp[N][N];
int book[N][N][4][5]; //到达同一个格子时可能处于不同的状态,附加两个因素,朝向(4个)、地面颜色(5个)
struct node {
int x, y, d, c; //0-北 1-东 2-南 3-西 0-绿色
node(int x, int y, int d, int c) : x(x), y(y), d(d), c(c) {}
};
//方向 0-北 1-东 2-南 3-西
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
void BFS() {
memset(book, -1, sizeof(book));
queue<node> q;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if (mp[i][j] == 'S')
q.push(node(i, j, 0, 0));
while (!q.empty()) {
node now = q.front();
q.pop();
if (mp[now.x][now.y] == 'T' && now.c == 0) {
printf("minimum time = %d sec\n", book[now.x][now.y][now.d][0] + 1);
return;
}
int x = now.x + dx[now.d], y = now.y + dy[now.d];
if (x >= 1 && x <= m && y >= 1 && y <= n && mp[x][y] != '#') {
int nColor = (now.c + 1) % 5;
if (book[x][y][now.d][nColor] == -1) {
book[x][y][now.d][nColor] = book[now.x][now.y][now.d][now.c] + 1;
q.push(node(x, y, now.d, nColor));
}
}
int nDir;
nDir = (now.d + 1) % 4;
if (book[now.x][now.y][nDir][now.c] == -1) {
book[now.x][now.y][nDir][now.c] = book[now.x][now.y][now.d][now.c] + 1;
q.push(node(now.x, now.y, nDir, now.c));
}
nDir = ((now.d - 1) % 4 + 4) % 4;
if (book[now.x][now.y][nDir][now.c] == -1) {
book[now.x][now.y][nDir][now.c] = book[now.x][now.y][now.d][now.c] + 1;
q.push(node(now.x, now.y, nDir, now.c));
}
}
printf("destination not reachable\n");
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
#endif
int T = 0;
while (scanf("%d%d", &m, &n) != EOF && m && n) {
memset(mp, '\0', sizeof(mp));
for (int i = 1; i <= m; i++) {
scanf("%s", mp[i] + 1);
}
if (T) printf("\n");
printf("Case #%d\n", ++T);
BFS();
}
return 0;
}