(UVa 10047) The Monocycle -- BFS 4维状态

题目链接:
http://acm.hust.edu.cn/vjudge/problem/19491

问题描述:
独轮车是一种仅有一个轮子的特殊自行车。他的轮子被等分为5份,分别上5中不同的颜色。现在有一个独轮车在一个M*N的网格上,每个网格的大小恰好使当车骑到下一个格子时,轮子恰好转过一个扇形,即恰好达到下一个颜色。车每秒可以在当前方向上前进一格,或者左转和右转(不移动,且颜色不变)。刚开始时他面向北颜色是绿色,位于S处,问他到达T处且颜色也是绿色的最短时间。如果不可能则输出:destination not reachable

分析:
这看上去也是一个用bfs求最短路的题,只不过在里面加了两个状态:方向和颜色。那我们怎么处理呢?我们令五种颜色为0,1,2,3,4。每次变颜色就加1并%5就可以了。那么颜色了,要加1和减1吗?总共有4其实减1等价于加3并%4就可以了。每次转移状态也只有左转,右转,前进3中方式。

关于bfs的迷宫问题,不管今后多加了几个状态,我们只要多加几维数组表示各种状态就可以了。

AC代码:

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;

const int INF = 1000000000;
const int maxr = 25 + 5;
const int maxc = 25 + 5;
int R, C, sr, sc, tr, tc;
char maze[maxr][maxc];

struct State {
  int r, c, dir, color;
  State(int r, int c, int dir, int color):r(r),c(c),dir(dir),color(color) {}
};

const int dr[] = {-1,0,1,0}; // north, west, south, east方向与编号对应
const int dc[] = {0,-1,0,1};
int d[maxr][maxc][4][5], vis[maxr][maxc][4][5];//4个方向,5种颜色

int ans;
queue<State> Q;

void update(int r, int c, int dir, int color, int v) {
  if(r < 0 || r >= R || c < 0 || c >= C) return; // 不能走出边界
  if(maze[r][c] == '.' && !vis[r][c][dir][color]) {
    Q.push(State(r, c, dir, color));
    vis[r][c][dir][color] = 1;
    d[r][c][dir][color] = v;
    if(r == tr && c == tc && color == 0) ans = min(ans, v); // 更新答案
  }
}

void bfs(State st) {
  d[st.r][st.c][st.dir][st.color] = 0;
  vis[st.r][st.c][st.dir][st.color] = 1;
  Q.push(st);
  while(!Q.empty()) {
    st = Q.front(); Q.pop();
    int v = d[st.r][st.c][st.dir][st.color] + 1;
    update(st.r, st.c, (st.dir+1)%4, st.color, v); // 左转
    update(st.r, st.c, (st.dir+3)%4, st.color, v); // 右转
    update(st.r+dr[st.dir], st.c+dc[st.dir], st.dir, (st.color+1)%5, v); // 前进
  }
}

int main() {
  int kase = 0;
  while(scanf("%d%d", &R, &C) == 2 && R && C) {
    for(int i = 0; i < R; i++) {
      scanf("%s", maze[i]);
      for(int j = 0; j < C; j++)
        if(maze[i][j] == 'S') { sr = i; sc = j; }
        else if(maze[i][j] == 'T') { tr = i; tc = j; }
    }
    maze[sr][sc] = maze[tr][tc] = '.';
    ans = INF;
    memset(vis, 0, sizeof(vis));
    bfs(State(sr, sc, 0, 0));

    if(kase > 0) printf("\n");
    printf("Case #%d\n", ++kase);
    if(ans == INF) printf("destination not reachable\n");
    else printf("minimum time = %d sec\n", ans);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值