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

    (上接迷宫递归算法)

    顺便也把图里求迷宫最短路径算法贴出来,主要思想是利用队列,采用广度优先搜索法,当第一次出现目的点时,中断搜索,并输出路径。程序还是主要使用的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;
        }

    
    }

    
 
  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值