hdoj 1253 胜利大逃亡 宽度优先遍历

来源:互联网 发布:算法设计与分析考试题 编辑:程序博客网 时间:2024/06/05 06:16

题目大意:3维空间找最短距离,加了个时间约束条件

解题思路:这题算是水题了,最短距离,宽度优先遍历就可以了,加个时间约束条件,到达那个时间的节点就不扩展了

之前没剪枝,超时了,网上有人不剪枝就过了,可能是因为使用了标准库的队列的缘故,超时后然后加个剪枝,对些当前节点到最终节点经过的格子数超过剩余时间的节点剪枝

最终过了,不过时间消耗也很大。。。。。

#include <iostream>#include <cstdio>#include <queue>#include <cstring>#include <algorithm>using namespace std;const int maxn = 51;struct node{    int x, y, z, step, ti;};int a, b, c, t;int maze[maxn][maxn][maxn];int dir[6][3] = {{1,0 ,0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};int bfs();int main(){       int test;    scanf("%d", &test);    while(test-- != 0)    {        scanf("%d %d %d %d", &a, &b, &c, &t);        for(int i = 0; i < a; i++)        {            for(int j = 0; j < b; j++)            {                for(int k = 0; k < c; k++)                    scanf("%d", &maze[i][j][k]);            }        }        int ans = bfs();        if(ans == -1)            printf("-1\n");        else            printf("%d\n", ans);    }        return 0;}int bfs(){    queue<node> que;    node s;    s.x = s.y = s.z = s.step = s.ti = 0;    que.push(s);    while(!que.empty())    {        node tmp = que.front();        que.pop();        if(tmp.ti <= t && tmp.x == a - 1 && tmp.y == b - 1 && tmp.z == c - 1)            return tmp.step;        if(tmp.ti >= t)            continue;        for(int i = 0; i < 6; i++)        {            int dx = tmp.x + dir[i][0];            int dy = tmp.y + dir[i][1];            int dz = tmp.z + dir[i][2];            if(dx >= 0 && dx < a && dy >= 0 && dy < b && dz >= 0 && dz < c && maze[dx][dy][dz] != 1)            {                int sx = abs(a - 1 - dx);                int sy = abs(b - 1 - dy);                int sz = abs(c - 1 - dz);                if((sx + sy + sz ) <= (t - tmp.ti) )                {                    maze[dx][dy][dz] = 1;                    node in;                    in.x = dx;                    in.y = dy;                    in.z = dz;                    in.step = tmp.step + 1;                    in.ti = tmp.ti + 1;                    que.push(in);                }            }        }    }    return -1;}


 

原创粉丝点击