ZOJ 1438.Asteroids!

三维迷宫,简单BFS


#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct Point{
    int x;
    int y;
    int z;
    int steps;
}start,end;             //起点与终点
int n;                  //层数
char ***space;          //保存太空
queue<Point> q;         //BFS队列
int move[6][3] = {{-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1}};
void Create(){
    //初始化太空
    space = new char**[n + 2];
    int i,j,k;
    for(i=0; i<n+2; i++){
        space[i] = new char*[n + 2];
        for(j=0; j<n+2; j++){
            space[i][j] = new char[n + 2];
        }
    }
    for(j=0; j<n+2; j++){
        for(k=0; k<n+2; k++){
            space[0][j][k] = space[n+1][j][k] = 'X';
        }
    }
    for(i=1; i<=n; i++){
        for(j=0; j<n+2; j++){
            space[i][j][0] = space[i][j][n+1] = 'X';
        }
        for(k=0; k<n+2; k++){
            space[i][0][k] = space[i][n+1][k] = 'X';
        }
    }
    for(i=1; i<=n; i++){
        for(j=1; j<=n; j++){
            for(k=1; k<=n; k++){
                cin>>space[i][j][k];
            }
        }
    }
    cin>>start.z>>start.y>>start.x;
    cin>>end.z>>end.y>>end.x;
    start.z++;start.y++;start.x++;start.steps = 0;
    end.z++;end.y++;end.x++;
    q.push(start);
}
int BFS(){
    //最短路径
    if(start.x == end.x && start.y == end.y && start.z == end.z)return 0;
    while(!q.empty()){
        start = q.front();
        q.pop();
        for(int i=0; i<6; i++){
            Point temp;
            temp.x = start.x + move[i][0];
            temp.y = start.y + move[i][1];
            temp.z = start.z + move[i][2];
            temp.steps = start.steps + 1;
            if(temp.x == end.x && temp.y == end.y && temp.z == end.z)return temp.steps;
            if(space[temp.x][temp.y][temp.z] == 'O'){
                space[temp.x][temp.y][temp.z] = 'X';
                q.push(temp);
            }
        }
    }
    return -1;
}
int main(){
    string s;       //输入
    while(cin>>s>>n){
        Create();
        cin>>s;
        int steps = BFS();
        if(steps == -1)cout<<"NO ROUTE"<<endl;
        else cout<<n<<' '<<steps<<endl;
        while(!q.empty())q.pop();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值