您的位置:首页 > 其它

UVA - 10047 The Monocycle (BFS)

2015-07-25 12:19 423 查看
题目大意:有一个n*m的网格,网格上面有的地方有障碍物

现在有一个人,骑着独轮车,要求从一个地方到达另一个地方,骑独轮车时,只能直走,或者左拐,右拐,不能向后走

独轮车的轮子被分成了5部分,每部分都有对应的颜色,刚开始时是绿色向下,当经过一个格子时,颜色就会变换

问从起点出发到终点,到终点时独轮车的绿色颜色向下,需要多久

解题思路:暴力BFS

[code]#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define N 30

struct Node{
    int x, y, dir, time, color;
}start;

int dir[4][2] = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};
int g

, vis

[5][4];
char str
;
int end_x, end_y, n, m;

void init() {

    for (int i = 0; i < n; i++) {
        scanf("%s", str);
        for (int j = 0; j < m; j++) {
            if (str[j] == '#') {
                g[i][j] = 1;
            }
            else {
                g[i][j] = 0;
                if (str[j] == 'S') {
                    start.x = i;
                    start.y = j;
                }
                if (str[j] == 'T') {
                    end_x = i;
                    end_y = j;
                }
            }
        }
    }
    memset(vis, 0, sizeof(vis));
}

void solve() {
    queue<Node> q;
    start.color = 0;
    start.time = 0;
    start.dir = 0;
    q.push(start);
    vis[start.x][start.y][0][0] = 1;

    while (!q.empty()) {
        Node t = q.front();
        q.pop();

        if (t.x == end_x && t.y == end_y && t.color == 0) {
            printf("minimum time = %d sec\n", t.time);
            return ;
        }

        for (int i = 0; i < 4; i++) {
            if (t.dir + i == 3)
                continue;
            Node tt;
            tt.x = t.x;
            tt.y = t.y;
            tt.color = t.color;
            tt.time = t.time + 1;
            tt.dir = t.dir;
            if(tt.dir == i) {
                tt.x += dir[tt.dir][0];
                tt.y += dir[tt.dir][1];
                tt.color = (tt.color + 1) % 5;
                if(tt.x < 0 || tt.x >= n || tt.y < 0 || tt.y >= m || g[tt.x][tt.y] || vis[tt.x][tt.y][tt.color][tt.dir])
                    continue;
                vis[tt.x][tt.y][tt.color][tt.dir] = 1;
                q.push(tt);
            }
            else {
                tt.dir = i;
                if(!vis[tt.x][tt.y][tt.color][tt.dir]) {
                    vis[tt.x][tt.y][tt.color][tt.dir] = 1;
                    q.push(tt);
                }
            }
        }
    }
    printf("destination not reachable\n");
}

int main() {
    int cas = 1;
    int flag = 0;
    while (scanf("%d%d", &n, &m) != EOF && n + m) {
        if(flag)
            printf("\n");
        else
            flag = 1;

        init();
        printf("Case #%d\n", cas++);
        solve();

    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: