zoukankan      html  css  js  c++  java
  • 搜索之广度优先【三维迷宫】(判断从一点能否到达另一点,最少走几步)

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #include <queue>
    #include<algorithm>
    using namespace std;
    #define N 11
    typedef struct
    {
    int x,y,z,steps;
    }triPoint;


    char map[N][N][N];
    int n;
    triPoint start, end;
    int dir[6][3]={{1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1}};


    int bfs(triPoint start)
    {
    queue<triPoint>q;
    int i;
    triPoint cur,next;

    //考虑起点和终点相同的情况
    if(start.x==end.x && start.y==end.y && start.z==end.z)
    {
    return 0;
    }

    start.steps=0;
    map[start.x][start.y][start.z]='X';
    q.push(start);
    while(!q.empty())
    {
    //取队首元素
    cur=q.front();
    q.pop();

    //广度优先搜索
    for(i=0;i<6;i++)
    {
    next.x=cur.x+dir[i][0];
    next.y=cur.y+dir[i][1];
    next.z=cur.z+dir[i][2];

    if(next.x==end.x && next.y==end.y && next.z==end.z) //下一步就是目的地
    {
    return cur.steps+1;
    }
    if(next.x>=0 && next.x<n && next.y>=0 && next.y<n && next.z>=0 && next.z<n)//下一步不越界
    if(map[next.x][next.y][next.z]!='X') //下一步不是星星
    {
    map[next.x][next.y][next.z]='X';
    next.steps=cur.steps+1;
    q.push(next);
    }//if
    }//for
    }//while
    return -1;
    }

    int main()
    {
    int i,j,steps;
    char str[N];
    while(scanf("START %d",&n)!=EOF)
    {
    for(i=0;i<n;i++)
    for(j=0;j<n;j++)
    scanf("%s",map[i][j]);
    scanf("%d%d%d",&start.x, &start.y, &start.z);
    scanf("%d%d%d",&end.x, &end.y, &end.z);
    scanf("%s", str);
    gets(str);
    steps=bfs(start);
    if(steps>=0)
    printf("%d %d/n",n,steps);
    else
    printf("NO ROUTE/n");
    }

    return 0;
    }
  • 相关阅读:
    【C++】基础及引用
    gradle打包分编译环境
    gradle
    MediaPlayer滑动不准的问题
    python初步入门
    音频播放服务
    《深入理解Android2》读书笔记(二)
    缓存(LruCache)机制
    handler机制
    监听网络状态
  • 原文地址:https://www.cnblogs.com/qiufeihai/p/2329741.html
Copyright © 2011-2022 走看看