码迷,mamicode.com
首页 > 其他好文 > 详细

HDOJ 1253 胜利大逃亡(bfs)

时间:2015-04-30 21:46:58      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

题目链接: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\n", Bfs());
    }
    return 0;
}

HDOJ 1253 胜利大逃亡(bfs)

标签:

原文地址:http://www.cnblogs.com/tallisHe/p/4469888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!