搜索--九度1456.[BFS]

题目[胜利大逃亡]:http://ac.jobdu.com/problem.php?pid=1456

坐标变换数组是一种很好的形式,以后多尝试
#include<cstdio>
#include<queue>
using namespace std;

int cas[51][51][51] = { 0 }; //坐标点
int mark[51][51][51] = { 0 }; //是否已访问
int a, b, c, t;

int go[][3] = { //坐标变换数组
    1,0,0,
    -1,0,0,
    0,1,0,
    0,-1,0,
    0,0,1,
    0,0,-1
};

struct point {
    int x, y, z;//坐标
    int time; //访问到本点的最短时间
};
queue<point> N; //队列

int BFS() {

    while (!N.empty()) {//非空
        point temp = N.front(); // 出队列
        N.pop(); 
        point now;
        for (int i = 0; i < 6; i++) {
            now.x = temp.x + go[i][0];
            now.y = temp.y + go[i][1];
            now.z = temp.z + go[i][2];
            now.time = temp.time + 1;

            if (now.x < 0 || now.x >= a || now.y < 0
                || now.y >= b || now.z < 0 || now.z >= c)//区域外
                continue;
            if (1 == mark[now.x][now.y][now.z]) continue; //已访问
            if (1 == cas[now.x][now.y][now.z]) continue; //墙

            N.push(now); //入队列
            mark[now.x][now.y][now.z] = 1;
            if (a - 1 == now.x && b - 1 == now.y 
                && c - 1 == now.z)//到达终点
                return now.time;
        }
    }
    return -1;
}

int main() {
    int n;
    scanf("%d", &n);
    while (n-- > 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", &cas[i][j][k]);
                    mark[i][j][k] = 0;
                }

        while (N.empty() == false) N.pop(); //清队列
        point temp;
        temp.x = temp.y = temp.z = temp.time = 0;
        N.push(temp); // 零点入队列
        int BFS_minT = BFS();

        if (BFS_minT <= t)
            printf("%d\n", BFS_minT);
        else
            printf("-1\n");

    }//while
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值