迷宫最短路径算法(使用队列)

    (上接迷宫递归算法)

    顺便也把图里求迷宫最短路径算法贴出来,主要思想是利用队列,采用广度优先搜索法,当第一次出现目的点时,中断搜索,并输出路径。程序还是主要使用的C语言,对于队列操作我又重写了下基本操作代码比如入队、出队等,没办法对C++不熟啊!!

   个人认为需要说明的是:

   1. 为了记录路径,借鉴了树的双亲表示法,所以队列中的数组元素定义如下

   

《迷宫最短路径算法(使用队列)》
《迷宫最短路径算法(使用队列)》
typedef 
struct
  

{
《迷宫最短路径算法(使用队列)》    
int location;     //(x-1)*3+y 
《迷宫最短路径算法(使用队列)》
    int parent;       //记录上一个节点即路径中前驱节点,方便最后输出
《迷宫最短路径算法(使用队列)》
}

QueueNode;

 

   2.仍然采用了上面的映射思想,公式也是 location=(x-1)*3+y

  

《迷宫最短路径算法(使用队列)》
void
 Maze_Shortest(
int
 maze[][
5
],point 
&
start,point 
&
des)
《迷宫最短路径算法(使用队列)》《迷宫最短路径算法(使用队列)》


{
《迷宫最短路径算法(使用队列)》    queue Queue;
《迷宫最短路径算法(使用队列)》    InitializeQueue(Queue);
《迷宫最短路径算法(使用队列)》    EnterQueue(Queue,(start.x
1)*5+start.y,Queue.head);
《迷宫最短路径算法(使用队列)》    
《迷宫最短路径算法(使用队列)》    
int direction;
《迷宫最短路径算法(使用队列)》    
bool FindFlag=false;  
《迷宫最短路径算法(使用队列)》《迷宫最短路径算法(使用队列)》    
int dir[4][2]={{1,0},{0,1},{1,0},{0,1}};
《迷宫最短路径算法(使用队列)》
《迷宫最短路径算法(使用队列)》    
while (!EmptyQueue(Queue)&&!FindFlag)
《迷宫最短路径算法(使用队列)》《迷宫最短路径算法(使用队列)》    
{
《迷宫最短路径算法(使用队列)》        
int curX=Queue.array[Queue.head].location/3+1;
《迷宫最短路径算法(使用队列)》        
int curY=Queue.array[Queue.head].location%3;
《迷宫最短路径算法(使用队列)》
《迷宫最短路径算法(使用队列)》        
for (direction=0;direction<4;direction++)          //遍历该点四周四个邻接点
《迷宫最短路径算法(使用队列)》《迷宫最短路径算法(使用队列)》        
{
《迷宫最短路径算法(使用队列)》            
int nextX=curX+dir[direction][0];
《迷宫最短路径算法(使用队列)》            
int nextY=curY+dir[direction][1];
《迷宫最短路径算法(使用队列)》            
if (!maze[nextX][nextY])                                     //如果为0 排除了墙和已经踩过的路
《迷宫最短路径算法(使用队列)》《迷宫最短路径算法(使用队列)》            
{
《迷宫最短路径算法(使用队列)》                EnterQueue(Queue,(nextX
1)*3+nextY,Queue.head);     //入队,入队元素是映射后节点!
《迷宫最短路径算法(使用队列)》                
if (nextX==des.x&&nextY==des.y)
《迷宫最短路径算法(使用队列)》《迷宫最短路径算法(使用队列)》                
{
《迷宫最短路径算法(使用队列)》                    FindFlag
=true;
《迷宫最短路径算法(使用队列)》                    
break;
《迷宫最短路径算法(使用队列)》                }

《迷宫最短路径算法(使用队列)》            }

《迷宫最短路径算法(使用队列)》        }

《迷宫最短路径算法(使用队列)》        Queue.head
++;
《迷宫最短路径算法(使用队列)》    }

《迷宫最短路径算法(使用队列)》    
if (EmptyQueue(Queue))
《迷宫最短路径算法(使用队列)》《迷宫最短路径算法(使用队列)》    
{
《迷宫最短路径算法(使用队列)》        printf(
找不到路径 );
《迷宫最短路径算法(使用队列)》    }

《迷宫最短路径算法(使用队列)》    
if(FindFlag)
《迷宫最短路径算法(使用队列)》《迷宫最短路径算法(使用队列)》    
{
《迷宫最短路径算法(使用队列)》        
int pre=Queue.array[Queue.rear].parent;
《迷宫最短路径算法(使用队列)》        Queue.array[
1].parent=0;
《迷宫最短路径算法(使用队列)》        printf(
%d<- ,Queue.array[Queue.rear].location);
《迷宫最短路径算法(使用队列)》        
while (pre)                                                   //迭代输出路径,可惜是逆向输出,不过可以用栈解决
《迷宫最短路径算法(使用队列)》《迷宫最短路径算法(使用队列)》
        {
《迷宫最短路径算法(使用队列)》            printf(
%d<- ,Queue.array[pre].location);
《迷宫最短路径算法(使用队列)》            pre
=Queue.array[pre].parent;
《迷宫最短路径算法(使用队列)》        }

《迷宫最短路径算法(使用队列)》    
《迷宫最短路径算法(使用队列)》    }

《迷宫最短路径算法(使用队列)》    
 

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/littlehedgehog/article/details/1758570
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞