• HDOJ 1253 胜利大逃亡(bfs)


    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1253

    思路分析:因为问题需要寻找到达终点的最短的距离(最短的步数),即在状态转换图上需要找出层次最浅的的状态(A-1, B-1, C-1),

    所以采用bfs更快能找出答案;另外,若采用dfs则比较困难,需要遍历所有的状态才能找出结果。

    代码如下

    #include <cstdio>
    #include <iostream>
    
    const int MAX_N = 60;
    struct Point
    {
        int a, b, c;
        int time;
        Point() { a = 0; b = 0; c = 0; time = 0; }
        Point(int x, int y, int z, int step_time)
        {
            a = x; b = y; c = z; time = step_time;
        }
    };
    
    int ans = 0;
    int A, B, C, game_times;
    int map[MAX_N][MAX_N][MAX_N];
    int move[6][3] =
    {{0, 0, -1}, {0, 0, 1}, {0, -1, 0}, {0, 1, 0}, {-1, 0, 0}, {1, 0, 0}};
    Point queue[1000000];
    
    int Bfs()
    {
        int head, tail;
        Point temp;
    
        head = tail = 0;
        temp.a = temp.b = temp.c = temp.time = 0;
        queue[tail++] = temp;
    
        while (head != tail)
        {
            temp = queue[head++];
            for (int i = 0; i < 6; ++i)
            {
                int next_a = temp.a + move[i][0];
                int next_b = temp.b + move[i][1];
                int next_c = temp.c + move[i][2];
    
                if (next_a < 0 || next_b < 0 || next_c < 0
                    || next_a >= A || next_b >= B || next_c >= C
                    || map[next_a][next_b][next_c] > 0 || temp.time + 1 > game_times)
                    continue;
    
                if (next_a == A - 1 && next_b == B - 1 && next_c == C - 1)
                    return temp.time + 1;
    
                Point next(next_a, next_b, next_c, temp.time + 1);
                map[next_a][next_b][next_c] = next.time;
                queue[tail++] = next;
            }
        }
        return  -1;
    }
    
    int main()
    {
        int k;
    
        scanf("%d", &k);
        while (k--)
        {
            scanf("%d %d %d %d", &A, &B, &C, &game_times);
            for (int i = 0; i < A; ++i)
            for (int j = 0; j < B; ++j)
            for (int k = 0; k < C; ++k)
                scanf("%d", &map[i][j][k]);
    
            printf("%d
    ", Bfs());
        }
        return 0;
    }
  • 相关阅读:
    android性能优化之布局优化
    android性能调优之traceview的使用
    android性能优化
    EditText光标居上
    ExecutorService的submit(Runnable x)和execute(Runnable x) 两个方法的本质区别
    android 静默安装
    android 内存优化
    image-webpack-loader在mac或ubuntu报错
    git重命名文件和文件夹
    js判断设备类型
  • 原文地址:https://www.cnblogs.com/tallisHe/p/4469888.html
Copyright © 2020-2023  润新知