路径规划(一): A*算法

简易地图

如图所示简易地图, 其中绿色方块的是起点 (用 A 表示), 中间蓝色的是障碍物, 红色的方块 (用 B 表示) 是目的地. 为了可以用一个二维数组来表示地图, 我们将地图划分成一个个的小方块.

二维数组在游戏中的应用是很多的, 比如贪吃蛇和俄罗斯方块基本原理就是移动方块而已. 而大型游戏的地图, 则是将各种"地貌"铺在这样的小方块上.

寻路步骤

1. 从起点A开始, 把它作为待处理的方格存入一个"开启列表", 开启列表就是一个等待检查方格的列表.

2. 寻找起点A周围可以到达的方格, 将它们放入"开启列表", 并设置它们的"父方格"为A.

3. 从"开启列表"中删除起点 A, 并将起点 A 加入"关闭列表", "关闭列表"中存放的都是不需要再次检查的方格

 图中浅绿色描边的方块表示已经加入 "开启列表" 等待检查. 淡蓝色描边的起点 A 表示已经放入 "关闭列表" , 它不需要再执行检查.

 从 "开启列表" 中找出相对最靠谱的方块, 什么是最靠谱? 它们通过公式 F=G+H 来计算.

 F = G + H

表示从起点 A 移动到网格上指定方格的移动耗费 (可沿斜方向移动).

表示从指定的方格移动到终点 B 的预计耗费 (H 有很多计算方法, 这里我们设定只可以上下左右移动).

我们假设横向移动一个格子的耗费为10, 为了便于计算, 沿斜方向移动一个格子耗费是14. 为了更直观的展示如何运算 FGH, 图中方块的左上角数字表示 F, 左下角表示 G, 右下角表示 H. 看看是否跟你心里想的结果一样?

从 "开启列表" 中选择 F 值最低的方格 C (绿色起始方块 A 右边的方块), 然后对它进行如下处理:

4. 把它从 "开启列表" 中删除, 并放到 "关闭列表" 中.

 5. 检查它所有相邻并且可以到达 (障碍物和 "关闭列表" 的方格都不考虑) 的方格. 如果这些方格还不在 "开启列表" 里的话, 将它们加入 "开启列表", 计算这些方格的 G, H 和 F 值各是多少, 并设置它们的 "父方格" 为 C.

6. 如果某个相邻方格 D 已经在 "开启列表" 里了, 检查如果用新的路径 (就是经过C 的路径) 到达它的话, G值是否会更低一些, 如果新的G值更低, 那就把它的 "父方格" 改为目前选中的方格 C, 然后重新计算它的 F 值和 G 值 (H 值不需要重新计算, 因为对于每个方块, H 值是不变的). 如果新的 G 值比较高, 就说明经过 C 再到达 D 不是一个明智的选择, 因为它需要更远的路, 这时我们什么也不做.

 如图, 我们选中了 C 因为它的 F 值最小, 我们把它从 "开启列表" 中删除, 并把它加入 "关闭列表". 它右边上下三个都是墙, 所以不考虑它们. 它左边是起始方块, 已经加入到 "关闭列表" 了, 也不考虑. 所以它周围的候选方块就只剩下 4 个. 让我们来看看 C 下面的那个格子, 它目前的 G 是14, 如果通过 C 到达它的话, G将会是 10 + 10, 这比 14 要大, 因此我们什么也不做.

然后我们继续从 "开启列表" 中找出 F 值最小的, 但我们发现 C 上面的和下面的同时为 54, 这时怎么办呢? 这时随便取哪一个都行, 比如我们选择了 C 下面的那个方块 D.

 D 右边已经右上方的都是墙, 所以不考虑, 但为什么右下角的没有被加进 "开启列表" 呢? 因为如果 C 下面的那块也不可以走, 想要到达 C 右下角的方块就需要从 "方块的角" 走了, 在程序中设置是否允许这样走. (图中的示例不允许这样走)

就这样, 我们从 "开启列表" 找出 F 值最小的, 将它从 "开启列表" 中移掉, 添加到 "关闭列表". 再继续找出它周围可以到达的方块, 如此循环下去...

那么什么时候停止呢? —— 当我们发现 "开始列表" 里出现了目标终点方块的时候, 说明路径已经被找到.

如何找回路径

如上图所示, 除了起始方块, 每一个曾经或者现在还在 "开启列表" 里的方块, 它都有一个 "父方块", 通过 "父方块" 可以索引到最初的 "起始方块", 这就是路径.

将整个过程抽象


 
 
  1. 把起始格添加到 "开启列表" 
  2. do 
  3. 寻找开启列表中F值最低的格子, 我们称它为当前格. 
  4.      把它切换到关闭列表. 
  5.      对当前格相邻的 8格中的每一个 
  6.      if (它不可通过 || 已经在 "关闭列表" 中) 
  7.   { 
  8.      什么也不做. 
  9.      } 
  10.          if (它不在开启列表中) 
  11.         { 
  12.          把它添加进 "开启列表", 把当前格作为这一格的父节点, 计算这一格的 FGH 
  13. }
  14.          if (它已经在开启列表中) 
  15.         { 
  16.          if (用 G 值为参考检查新的路径是否更好, 更低的G值意味着更好的路径) 
  17.          { 
  18.          把这一格的父节点改成当前格, 并且重新计算这一格的 GF 值. 
  19.                 } 
  20. }
  21. } while( 目标格已经在 "开启列表", 这时候路径被找到) 
  22. 如果开启列表已经空了, 说明路径不存在.
  23. 最后从目标格开始, 沿着每一格的父节点移动直到回到起始格, 这就是路径.

 

C++实现代码:

版本1:

Astar.h


 
 
  1. #pragma once
  2. /*
  3. //A*算法对象类
  4. */
  5. #include <vector>
  6. #include <list>
  7. const int kCost1 = 10; //直移一格消耗
  8. const int kCost2 = 14; //斜移一格消耗
  9. struct Point
  10. {
  11. int x, y; //点坐标,这里为了方便按照C++的数组来计算,x代表横排,y代表竖列
  12. int F, G, H; //F=G+H
  13. Point *parent; //parent的坐标,这里没有用指针,从而简化代码
  14. Point( int _x, int _y) :x(_x), y(_y), F( 0), G( 0), H( 0), parent( NULL) //变量初始化
  15. {
  16. }
  17. };
  18. class Astar
  19. {
  20. public:
  21. void InitAstar(std::vector<std::vector<int>> &_maze);
  22. std:: list<Point *> GetPath(Point &startPoint, Point &endPoint, bool isIgnoreCorner);
  23. private:
  24. Point *findPath(Point &startPoint, Point &endPoint, bool isIgnoreCorner);
  25. std:: vector<Point *> getSurroundPoints( const Point *point, bool isIgnoreCorner) const;
  26. bool isCanreach(const Point *point, const Point *target, bool isIgnoreCorner) const; //判断某点是否可以用于下一步判断
  27. Point *isInList(const std::list<Point *> &list, const Point *point) const; //判断开启/关闭列表中是否包含某点
  28. Point *getLeastFpoint(); //从开启列表中返回F值最小的节点
  29. //计算FGH值
  30. int calcG(Point *temp_start, Point *point);
  31. int calcH(Point *point, Point *end);
  32. int calcF(Point *point);
  33. private:
  34. std:: vector< std:: vector< int>> maze;
  35. std:: list<Point *> openList; //开启列表
  36. std:: list<Point *> closeList; //关闭列表
  37. };

Astar.cpp


 
 
  1. #include <math.h>
  2. #include "Astar.h"
  3. void Astar::InitAstar( std:: vector< std:: vector< int>> &_maze)
  4. {
  5. maze = _maze;
  6. }
  7. int Astar::calcG(Point *temp_start, Point *point)
  8. {
  9. int extraG = ( abs(point->x - temp_start->x) + abs(point->y - temp_start->y)) == 1 ? kCost1 : kCost2;
  10. int parentG = point->parent == NULL ? 0 : point->parent->G; //如果是初始节点,则其父节点是空
  11. return parentG + extraG;
  12. }
  13. int Astar::calcH(Point *point, Point *end)
  14. {
  15. //用简单的欧几里得距离计算H,这个H的计算是关键,还有很多算法,没深入研究^_^
  16. return sqrt(( double)(end->x - point->x)*( double)(end->x - point->x) + ( double)(end->y - point->y)*( double)(end->y - point->y))*kCost1;
  17. }
  18. int Astar::calcF(Point *point)
  19. {
  20. return point->G + point->H;
  21. }
  22. Point *Astar::getLeastFpoint()
  23. {
  24. if (!openList.empty())
  25. {
  26. auto resPoint = openList.front();
  27. for ( auto &point : openList)
  28. if (point->F<resPoint->F)
  29. resPoint = point;
  30. return resPoint;
  31. }
  32. return NULL;
  33. }
  34. Point *Astar::findPath(Point &startPoint, Point &endPoint, bool isIgnoreCorner)
  35. {
  36. openList.push_back( new Point(startPoint.x, startPoint.y)); //置入起点,拷贝开辟一个节点,内外隔离
  37. while (!openList.empty())
  38. {
  39. auto curPoint = getLeastFpoint(); //找到F值最小的点
  40. openList.remove(curPoint); //从开启列表中删除
  41. closeList.push_back(curPoint); //放到关闭列表
  42. //1,找到当前周围八个格中可以通过的格子
  43. auto surroundPoints = getSurroundPoints(curPoint, isIgnoreCorner);
  44. for ( auto &target : surroundPoints)
  45. {
  46. //2,对某一个格子,如果它不在开启列表中,加入到开启列表,设置当前格为其父节点,计算F G H
  47. if (!isInList(openList, target))
  48. {
  49. target->parent = curPoint;
  50. target->G = calcG(curPoint, target);
  51. target->H = calcH(target, &endPoint);
  52. target->F = calcF(target);
  53. openList.push_back(target);
  54. }
  55. //3,对某一个格子,它在开启列表中,计算G值, 如果比原来的大, 就什么都不做, 否则设置它的父节点为当前点,并更新G和F
  56. else
  57. {
  58. int tempG = calcG(curPoint, target);
  59. if (tempG<target->G)
  60. {
  61. target->parent = curPoint;
  62. target->G = tempG;
  63. target->F = calcF(target);
  64. }
  65. }
  66. Point *resPoint = isInList(openList, &endPoint);
  67. if (resPoint)
  68. return resPoint; //返回列表里的节点指针,不要用原来传入的endpoint指针,因为发生了深拷贝
  69. }
  70. }
  71. return NULL;
  72. }
  73. std:: list<Point *> Astar::GetPath(Point &startPoint, Point &endPoint, bool isIgnoreCorner)
  74. {
  75. Point *result = findPath(startPoint, endPoint, isIgnoreCorner);
  76. std:: list<Point *> path;
  77. //返回路径,如果没找到路径,返回空链表
  78. while (result)
  79. {
  80. path.push_front(result);
  81. result = result->parent;
  82. }
  83. // 清空临时开闭列表,防止重复执行GetPath导致结果异常
  84. openList.clear();
  85. closeList.clear();
  86. return path;
  87. }
  88. Point *Astar::isInList( const std:: list<Point *> & list, const Point *point) const
  89. {
  90. //判断某个节点是否在列表中,这里不能比较指针,因为每次加入列表是新开辟的节点,只能比较坐标
  91. for ( auto p : list)
  92. if (p->x == point->x&&p->y == point->y)
  93. return p;
  94. return NULL;
  95. }
  96. bool Astar::isCanreach( const Point *point, const Point *target, bool isIgnoreCorner) const
  97. {
  98. if (target->x< 0 || target->x>maze.size() - 1
  99. || target->y< 0 || target->y>maze[ 0].size() - 1
  100. || maze[target->x][target->y] == 1
  101. || target->x == point->x&&target->y == point->y
  102. || isInList(closeList, target)) //如果点与当前节点重合、超出地图、是障碍物、或者在关闭列表中,返回false
  103. return false;
  104. else
  105. {
  106. if ( abs(point->x - target->x) + abs(point->y - target->y) == 1) //非斜角可以
  107. return true;
  108. else
  109. {
  110. //斜对角要判断是否绊住
  111. if (maze[point->x][target->y] == 0 && maze[target->x][point->y] == 0)
  112. return true;
  113. else
  114. return isIgnoreCorner;
  115. }
  116. }
  117. }
  118. std:: vector<Point *> Astar::getSurroundPoints( const Point *point, bool isIgnoreCorner) const
  119. {
  120. std:: vector<Point *> surroundPoints;
  121. for ( int x = point->x - 1; x <= point->x + 1; x++)
  122. for ( int y = point->y - 1; y <= point->y + 1; y++)
  123. if (isCanreach(point, new Point(x, y), isIgnoreCorner))
  124. surroundPoints.push_back( new Point(x, y));
  125. return surroundPoints;
  126. }

main.cpp


 
 
  1. #include <iostream>
  2. #include "Astar.h"
  3. using namespace std;
  4. int main()
  5. {
  6. //初始化地图,用二维矩阵代表地图,1表示障碍物,0表示可通
  7. vector< vector< int>> maze = {
  8. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
  9. { 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1 },
  10. { 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1 },
  11. { 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1 },
  12. { 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1 },
  13. { 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 },
  14. { 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },
  15. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
  16. };
  17. Astar astar;
  18. astar.InitAstar(maze);
  19. //设置起始和结束点
  20. Point start(1, 1);
  21. Point end(6, 10);
  22. //A*算法找寻路径
  23. list<Point *> path = astar.GetPath(start, end, false);
  24. //打印
  25. for ( auto &p : path)
  26. cout << '(' << p->x << ',' << p->y << ')' << endl;
  27. system( "pause");
  28. return 0;
  29. }

版本2:

Astar.h


 
 
  1. #ifndef ASTAR_H
  2. #define ASTAR_H
  3. #include <iostream>
  4. #include <queue>
  5. #include <vector>
  6. #include <stack>
  7. #include<algorithm>
  8. using namespace std;
  9. typedef struct Node
  10. {
  11. int x, y;
  12. int g; //起始点到当前点实际代价
  13. int h; //当前节点到目标节点最佳路径的估计代价
  14. int f; //估计值
  15. Node* father;
  16. Node( int x, int y)
  17. {
  18. this->x = x;
  19. this->y = y;
  20. this->g = 0;
  21. this->h = 0;
  22. this->f = 0;
  23. this->father = NULL;
  24. }
  25. Node( int x, int y, Node* father)
  26. {
  27. this->x = x;
  28. this->y = y;
  29. this->g = 0;
  30. this->h = 0;
  31. this->f = 0;
  32. this->father = father;
  33. }
  34. }Node;
  35. class Astar{
  36. public:
  37. Astar();
  38. ~Astar();
  39. void search(Node* startPos, Node* endPos);
  40. void checkPoit(int x, int y, Node* father, int g);
  41. void NextStep(Node* currentPoint);
  42. int isContains(vector<Node*>* Nodelist, int x, int y);
  43. void countGHF(Node* sNode, Node* eNode, int g);
  44. static bool compare(Node* n1, Node* n2);
  45. bool unWalk(int x, int y);
  46. void printPath(Node* current);
  47. void printMap();
  48. vector<Node*> openList;
  49. vector<Node*> closeList;
  50. Node *startPos;
  51. Node *endPos;
  52. static const int WeightW = 10; // 正方向消耗
  53. static const int WeightWH = 14; //打斜方向的消耗
  54. static const int row = 6;
  55. static const int col = 8;
  56. };
  57. #endif

Astar.cpp


 
 
  1. #include "Astar.h"
  2. int map[ 101][ 101] =
  3. {
  4. { 0, 0, 0, 1, 0, 1, 0, 0, 0 },
  5. { 0, 0, 0, 1, 0, 1, 0, 0, 0 },
  6. { 0, 0, 0, 0, 0, 1, 0, 0, 0 },
  7. { 0, 0, 0, 1, 0, 1, 0, 1, 0 },
  8. { 0, 0, 0, 1, 0, 1, 0, 1, 0 },
  9. { 0, 0, 0, 1, 0, 0, 0, 1, 0 },
  10. { 0, 0, 0, 1, 0, 0, 0, 1, 0 }
  11. };
  12. Astar::Astar()
  13. {
  14. }
  15. Astar::~Astar()
  16. {
  17. }
  18. void Astar::search(Node* startPos, Node* endPos)
  19. {
  20. if (startPos->x < 0 || startPos->x > row || startPos->y < 0 || startPos->y >col ||
  21. endPos->x < 0 || endPos->x > row || endPos->y < 0 || endPos->y > col)
  22. return;
  23. Node* current;
  24. this->startPos = startPos;
  25. this->endPos = endPos;
  26. openList.push_back(startPos);
  27. //主要是这块,把开始的节点放入openlist后开始查找旁边的8个节点,如果坐标超长范围或在closelist就return 如果已经存在openlist就对比当前节点到遍历到的那个节点的G值和当前节点到原来父节点的G值 如果原来的G值比较大 不用管 否则重新赋值G值 父节点 和f 如果是新节点 加入到openlist 直到opellist为空或找到终点
  28. while (openList.size() > 0)
  29. {
  30. current = openList[ 0];
  31. if (current->x == endPos->x && current->y == endPos->y)
  32. {
  33. cout << "find the path" << endl;
  34. printMap();
  35. printPath(current);
  36. openList.clear();
  37. closeList.clear();
  38. break;
  39. }
  40. NextStep(current);
  41. closeList.push_back(current);
  42. openList.erase(openList.begin());
  43. sort(openList.begin(), openList.end(), compare);
  44. }
  45. }
  46. void Astar::checkPoit( int x, int y, Node* father, int g)
  47. {
  48. if (x < 0 || x > row || y < 0 || y > col)
  49. return;
  50. if ( this->unWalk(x, y))
  51. return;
  52. if (isContains(&closeList, x, y) != -1)
  53. return;
  54. int index;
  55. if ((index = isContains(&openList, x, y)) != -1)
  56. {
  57. Node *point = openList[index];
  58. if (point->g > father->g + g)
  59. {
  60. point->father = father;
  61. point->g = father->g + g;
  62. point->f = point->g + point->h;
  63. }
  64. }
  65. else
  66. {
  67. Node * point = new Node(x, y, father);
  68. countGHF(point, endPos, g);
  69. openList.push_back(point);
  70. }
  71. }
  72. void Astar::NextStep(Node* current)
  73. {
  74. checkPoit(current->x - 1, current->y, current, WeightW); //左
  75. checkPoit(current->x + 1, current->y, current, WeightW); //右
  76. checkPoit(current->x, current->y + 1, current, WeightW); //上
  77. checkPoit(current->x, current->y - 1, current, WeightW); //下
  78. checkPoit(current->x - 1, current->y + 1, current, WeightWH); //左上
  79. checkPoit(current->x - 1, current->y - 1, current, WeightWH); //左下
  80. checkPoit(current->x + 1, current->y - 1, current, WeightWH); //右下
  81. checkPoit(current->x + 1, current->y + 1, current, WeightWH); //右上
  82. }
  83. int Astar::isContains( vector<Node*>* Nodelist, int x, int y)
  84. {
  85. for ( int i = 0; i < Nodelist->size(); i++)
  86. {
  87. if (Nodelist->at(i)->x == x && Nodelist->at(i)->y == y)
  88. {
  89. return i;
  90. }
  91. }
  92. return -1;
  93. }
  94. void Astar::countGHF(Node* sNode, Node* eNode, int g)
  95. {
  96. int h = ( abs(sNode->x - eNode->x) + abs(sNode->y - eNode->y)) * WeightW;
  97. int currentg = sNode->father->g + g;
  98. int f = currentg + h;
  99. sNode->f = f;
  100. sNode->h = h;
  101. sNode->g = currentg;
  102. }
  103. bool Astar::compare(Node* n1, Node* n2)
  104. {
  105. //printf("%d,%d",n1->f,n2->f);
  106. return n1->f < n2->f;
  107. }
  108. bool Astar::unWalk( int x, int y)
  109. {
  110. if ( map[x][y] == 1)
  111. return true;
  112. return false;
  113. }
  114. void Astar::printPath(Node* current)
  115. {
  116. if (current->father != NULL)
  117. printPath(current->father);
  118. printf( "(%d,%d)", current->x, current->y);
  119. }
  120. void Astar::printMap()
  121. {
  122. for ( int i = 0; i <= row; i++){
  123. for ( int j = 0; j <= col; j++){
  124. printf( "%d ", map[i][j]);
  125. }
  126. printf( "\n");
  127. }
  128. }

main.cpp


 
 
  1. #include "Astar.h"
  2. int main(int argc, char* argv[])
  3. {
  4. Astar astar;
  5. Node *startPos = new Node( 5, 1);
  6. Node *endPos = new Node( 3, 8);
  7. astar.search(startPos, endPos);
  8. getchar();
  9. return 0;
  10. }

 

参考:

A* Pathfinding for Beginners

理解A*寻路算法具体过程

A星寻路算法介绍

寻路算法综述

  • 2
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值