UVA 10047 The Monocycle(BFS)

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=988

题意:从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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值