A* 算法及伪代码

Q:

1. 手工写出 A* 算法找到最短路的过程

2. 写出算法伪代码

A:

1. A*算法过程:

1.首先把起始位置点加入到一个称为“open List”的列表,在寻路的过程中,目前,我们可以认为open List这个列表会存放许多待测试的点,这些点是通往目标点的关键,以后会逐渐往里面添加更多的测试点,同时,为了效率考虑,通常这个列表是个已经排序的列表。

2.如果open List列表不为空,则重复以下工作:

(1)找出open List中通往目标点代价最小的点作为当前点;

(2)把当前点放入一个称为close List的列表;

(3)对当前点周围的4个点每个进行处理(这里是限制了斜向的移动),如果该点是可以通过并且该点不在close List列表中,则处理如下;

4)如果该点正好是目标点,则把当前点作为该点的父节点,并退出循环,设置已经找到路径标记;

(5)如果该点也不在open List中,则计算该节点到目标节点的代价,把当前点作为该点的父节点,并把该节点添加到open List中;

6)如果该点已经在open List中了,则比较该点和当前点通往目标点的代价,如果当前点的代价更小,则把当前点作为该点的父节点,同时,重新计算该点通往目标点的代价,并把open List重新排序;

3.完成以上循环后,如果已经找到路径,则从目标点开始,依次查找每个节点的父节点,直到找到开始点,这样就形成了一条路径。 

 

 

2.算法的伪代码

First create a data structure Node:

struct Node{

   int g;    // the g value of the node  

   int h;    // the h value of the node 

   int f;    // the f value of the node

   Node*pre; // pre node of the node

};

 

AStar_Search(){

   struct Node start_node;

   start_node.g = 0;

   start_node.h = H(start);

   start_node.f = start_node.h;

   start_node.pre = NULL;

   OPEN = [start_node]; CLOSE = [];

  

   while ( OPEN is not empty ) {

      The node with the smallest F value is obtained from the OPEN linked list,

      which is called x_node, and the corresponding node is called x;

      Remove x_node from the OPEN list;

      if (x is the end node){

          Return the path

          according to the pre pointer of the node structure corresponding to each node;

      }

      for (each successor node y of x){

          struct  Node  y_node;

          y_node.g = x_node.g+w(x,y);

          y_node.h = H(y);

          y_node.f = y_node.g+y_node.h;

          y.pre = x_node;

         

          if(y is not in the OPEN table and not in the CLOSE table){

             Put y_node in the OPEN table;

          }else  if(y is in the OPEN table){

             Take out the Node structure corresponding to the y node in the OPEN table,

             which is called y_open;

             if( y_node.f < y_open.f) {

                y_open.g = y_node.g;

                y_open.h = y_node.h;

                y_open.f = y_node.f;

                y_open.pre = y_node.pre;

             }

          }else{

             Take out the Node structure corresponding to the y node in the CLOSE table,

             which is called y_close;

             if(y_node.f < y_close.f){ 

                Remove y_close from the CLOSE list

                Put y_node in the OPEN table;

             }

          }

      }  //end for

     

      Put x_node into the CLOSE table;

   }  //end while

// end AStar_Search

猜你喜欢

转载自blog.csdn.net/weixin_43821874/article/details/94737711