独轮车(The Monocycle, UVa 10047)BFS

独轮车(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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值