UVA-10047
题意:独轮车有5个颜色,每一秒独轮车可以向前移动(面朝的方向移动一格)或者原地转90度(左右都行)。初始是绿色朝下,面向北面,初始位置为S。要求用多少秒能到达T并且还是绿色朝下。
解题思路:BFS,只不过除了常规的坐标XY之外多了方向D和颜色C。vis[x][y][d][c]。操作就是向前走一格以及左右旋转。假设初始5个颜色为01234,下一个颜色就是(c+1)%5。方向预设好移动数组,{{-1,0},{0,1},{1,0},{0,-1}},d+1就是右旋转,d-1就是左旋转。
/*************************************************************************
> File Name: UVA-10047.cpp
> Author: Narsh
>
> Created Time: 2016?07?21? ??? 14?24?46?
************************************************************************/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
struct node {
int x,y,d,c,t;
} q[600000];
const int C[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
int h,t,n,m,endx,endy;
int x,y,d,c;
bool vis[30][30][6][8];
char map[30][30];
int main() {
int num=0;
while (scanf("%d%d\n",&n,&m) && n+m) {
memset(vis,true,sizeof(vis));
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m+1; j++) {
scanf("%c",&map[i][j]);
if (map[i][j] == 'S') {
q[1].x=i;
q[1].y=j;
q[1].d=0;
q[1].c=0;
q[1].t=0;
vis[i][j][0][0]=false;
map[i][j] = '.';
}
if (map[i][j] == 'T') {
endx=i;
endy=j;
map[i][j]='.';
}
}
h=0;t=1;
while (h < t) {
h++;
x=q[h].x;y=q[h].y;d=q[h].d;c=q[h].c;
if (x == endx && y == endy && c == 0) break;
// go ahead
x=x+C[d][0];y=y+C[d][1];c=(c+1)%5;
if (1 <= x && x <= n && 1 <= y && y <= m && vis[x][y][d][c] && map[x][y] == '.') {
vis[x][y][d][c]=false;
t++;
q[t].x=x;
q[t].y=y;
q[t].d=d;
q[t].c=c;
q[t].t=q[h].t+1;
}
// turn right
x=q[h].x;y=q[h].y;d=q[h].d;c=q[h].c;
d=(d+1)%4;
if (1 <= x && x <= n && 1 <= y && y <= m && vis[x][y][d][c]) {
vis[x][y][d][c]=false;
t++;
q[t].x=x;
q[t].y=y;
q[t].d=d;
q[t].c=c;
q[t].t=q[h].t+1;
}
// truen left
x=q[h].x;y=q[h].y;d=q[h].d;c=q[h].c;
d=((d-1)%4+4)%4;
if (1 <= x && x <= n && 1 <= y && y <= m && vis[x][y][d][c]) {
vis[x][y][d][c]=false;
t++;
q[t].x=x;
q[t].y=y;
q[t].d=d;
q[t].c=c;
q[t].t=q[h].t+1;
}
}
if (num != 0) printf("\n");
num++;
printf("Case #%d\n",num);
if (q[h].x == endx && q[h].y == endy && q[h].c == 0)
printf("minimum time = %d sec\n",q[h].t);
else printf("destination not reachable\n");
}
}