算法——A*寻路(C++实现)


首先说明下,不知道为什么代码都重复了一遍,编辑的时候是不重复的,发布之后就这样了。

http://www.policyalmanac.org/games/aStarTutorial.htm   这是英文原文《A*入门》,最经典的讲解,有demo演示

http://www.cnblogs.com/technology/archive/2011/05/26/2058842.html  这是国人翻译后整理的简版,有简单代码demo,不过有些错误,讲得很清晰,本文图片来自这篇

http://blog.csdn.net/b2b160/article/details/4057781  一片关于寻路算法的综述


A*寻路算法是游戏中常用的AI算法,这里用C++简单实现了一下算法,便于理解。

搜索区域


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

开始寻路

  • 1.从起点A开始, 把它作为待处理的方格存入一个"开启列表", 开启列表就是一个等待检查方格的列表.
  • 2.寻找起点A周围可以到达的方格, 将它们放入"开启列表", 并设置它们的"父方格"为A.
  • 3.从"开启列表"中删除起点 A, 并将起点 A 加入"关闭列表", "关闭列表"中存放的都是不需要再次检查的方格

图中浅绿色描边的方块表示已经加入 "开启列表" 等待检查. 淡蓝色描边的起点 A 表示已经放入 "关闭列表" , 它不需要再执行检查.
从 "开启列表" 中找出相对最适宜的方块, 通过公式 F=G+H 来计算.
F = G + H
 G 表示从起点 A 移动到网格上指定方格的移动耗费 (可沿斜方向移动).
 H 表示从指定的方格移动到终点 B 的预计耗费 ( H 有很多计算方法, 本文代码使用简单的欧几里得距离计算方法).

我们假设横向移动一个格子的耗费为10, 为了便于计算, 沿斜方向移动一个格子耗费是14. 为了更直观的展示如何运算 FGH, 图中方块的左上角数字表示 F, 左下角表示 G, 右下角表示 H. 看看是否跟你心里想的结果一样?
从 "开启列表" 中选择 F 值最低的方格 C (绿色起始方块 A 右边的方块), 然后对它进行如下处理:
如果C上方和下方都是障碍物的话会走入死胡同吗?不会,根据算法,这时候C会被直接放到关闭列表,没有发生任何节点的F更新和父节点更新
  • 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 值最小的, 将它从 "开启列表" 中移掉, 添加到 "关闭列表". 再继续找出它周围可以到达的方块, 如此循环下去...
那么什么时候停止呢? —— 当我们发现 "开始列表" 里出现了目标终点方块的时候, 说明路径已经被找到.

输出路径


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

算法伪码

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

把起始格添加到 "开启列表" 
do 
{ 
       寻找开启列表中F值最低的格子, 我们称它为当前格. 
       把它切换到关闭列表. 
       对当前格相邻的8格中的每一个 
          if (它不可通过 || 已经在 "关闭列表" 中) 
          { 
                什么也不做. 
           } 
          if (它不在开启列表中) 
          { 
                把它添加进 "开启列表", 把当前格作为这一格的父节点, 计算这一格的 FGH 
          if (它已经在开启列表中) 
          { 
                if (用G值为参考检查新的路径是否更好, 更低的G值意味着更好的路径) 
                    { 
                            把这一格的父节点改成当前格, 并且重新计算这一格的 GF 值. 
                    } 
} while( 目标格已经在 "开启列表", 这时候路径被找到) 
如果开启列表已经空了, 说明路径不存在.

最后从目标格开始, 沿着每一格的父节点移动直到回到起始格, 这就是路径.

C++实现代码

Astar.h
#pragma once  
/* 
//A*算法对象类 
*/  
#include <vector>  
#include <list>  
  
const int kCost1=10; //直移一格消耗  
const int kCost2=14; //斜移一格消耗  
  
struct Point  
{  
    int x,y; //点坐标,这里为了方便按照C++的数组来计算,x代表横排,y代表竖列  
    int F,G,H; //F=G+H  
    Point *parent; //parent的坐标,这里没有用指针,从而简化代码  
    Point(int _x,int _y):x(_x),y(_y),F(0),G(0),H(0),parent(NULL)  //变量初始化  
    {  
    }  
};  
  
  
class Astar  
{  
public:  
    void InitAstar(std::vector<std::vector<int>> &_maze);  
    std::list<Point *> GetPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner);  
  
private:  
    Point *findPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner);  
    std::vector<Point *> getSurroundPoints(const Point *point,bool isIgnoreCorner) const;  
    bool isCanreach(const Point *point,const Point *target,bool isIgnoreCorner) const; //判断某点是否可以用于下一步判断  
    Point *isInList(const std::list<Point *> &list,const Point *point) const; //判断开启/关闭列表中是否包含某点  
    Point *getLeastFpoint(); //从开启列表中返回F值最小的节点  
    //计算FGH值  
    int calcG(Point *temp_start,Point *point);  
    int calcH(Point *point,Point *end);  
    int calcF(Point *point);  
private:  
    std::vector<std::vector<int>> maze;  
    std::list<Point *> openList;  //开启列表  
    std::list<Point *> closeList; //关闭列表  
};  

#pragma once
/*
//A*算法对象类
*/
#include <vector>
#include <list>

const int kCost1=10; //直移一格消耗
const int kCost2=14; //斜移一格消耗

struct Point
{
	int x,y; //点坐标,这里为了方便按照C++的数组来计算,x代表横排,y代表竖列
	int F,G,H; //F=G+H
	Point *parent; //parent的坐标,这里没有用指针,从而简化代码
	Point(int _x,int _y):x(_x),y(_y),F(0),G(0),H(0),parent(NULL)  //变量初始化
	{
	}
};


class Astar
{
public:
	void InitAstar(std::vector<std::vector<int>> &_maze);
	std::list<Point *> GetPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner);

private:
	Point *findPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner);
	std::vector<Point *> getSurroundPoints(const Point *point,bool isIgnoreCorner) const;
	bool isCanreach(const Point *point,const Point *target,bool isIgnoreCorner) const; //判断某点是否可以用于下一步判断
	Point *isInList(const std::list<Point *> &list,const Point *point) const; //判断开启/关闭列表中是否包含某点
	Point *getLeastFpoint(); //从开启列表中返回F值最小的节点
	//计算FGH值
	int calcG(Point *temp_start,Point *point);
	int calcH(Point *point,Point *end);
	int calcF(Point *point);
private:
	std::vector<std::vector<int>> maze;
	std::list<Point *> openList;  //开启列表
	std::list<Point *> closeList; //关闭列表
};

Astar.cpp
#include <math.h>  
#include "Astar.h"  
  
void Astar::InitAstar(std::vector<std::vector<int>> &_maze)  
{  
    maze=_maze;  
}  
  
int Astar::calcG(Point *temp_start,Point *point)  
{  
    int extraG=(abs(point->x-temp_start->x)+abs(point->y-temp_start->y))==1?kCost1:kCost2;  
    int parentG=point->parent==NULL?0:point->parent->G; //如果是初始节点,则其父节点是空  
    return parentG+extraG;  
}  
  
int Astar::calcH(Point *point,Point *end)  
{  
    //用简单的欧几里得距离计算H,这个H的计算是关键,还有很多算法,没深入研究^_^  
    return sqrt((double)(end->x-point->x)*(double)(end->x-point->x)+(double)(end->y-point->y)*(double)(end->y-point->y))*kCost1;  
}  
  
int Astar::calcF(Point *point)  
{  
    return point->G+point->H;  
}  
  
Point *Astar::getLeastFpoint()  
{  
    if(!openList.empty())  
    {  
        auto resPoint=openList.front();  
        for(auto &point:openList)  
            if(point->F<resPoint->F)  
                resPoint=point;  
        return resPoint;  
    }  
    return NULL;  
}  
  
Point *Astar::findPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner)  
{  
    openList.push_back(new Point(startPoint.x,startPoint.y)); //置入起点,拷贝开辟一个节点,内外隔离  
    while(!openList.empty())  
    {  
        auto curPoint=getLeastFpoint(); //找到F值最小的点  
        openList.remove(curPoint); //从开启列表中删除  
        closeList.push_back(curPoint); //放到关闭列表  
        //1,找到当前周围八个格中可以通过的格子  
        auto surroundPoints=getSurroundPoints(curPoint,isIgnoreCorner);  
        for(auto &target:surroundPoints)  
        {  
            //2,对某一个格子,如果它不在开启列表中,加入到开启列表,设置当前格为其父节点,计算F G H  
            if(!isInList(openList,target))  
            {  
                target->parent=curPoint;  
  
                target->G=calcG(curPoint,target);  
                target->H=calcH(target,&endPoint);  
                target->F=calcF(target);  
  
                openList.push_back(target);  
            }  
            //3,对某一个格子,它在开启列表中,计算G值, 如果比原来的大, 就什么都不做, 否则设置它的父节点为当前点,并更新G和F  
            else  
            {  
                int tempG=calcG(curPoint,target);  
                if(tempG<target->G)  
                {  
                    target->parent=curPoint;  
  
                    target->G=tempG;  
                    target->F=calcF(target);  
                }  
            }  
            Point *resPoint=isInList(openList,&endPoint);  
            if(resPoint)  
                return resPoint; //返回列表里的节点指针,不要用原来传入的endpoint指针,因为发生了深拷贝  
        }  
    }  
  
    return NULL;  
}  
  
std::list<Point *> Astar::GetPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner)  
{  
    Point *result=findPath(startPoint,endPoint,isIgnoreCorner);  
    std::list<Point *> path;  
    //返回路径,如果没找到路径,返回空链表  
    while(result)  
    {  
        path.push_front(result);  
        result=result->parent;  
    }  
    return path;  
}  
  
Point *Astar::isInList(const std::list<Point *> &list,const Point *point) const  
{  
    //判断某个节点是否在列表中,这里不能比较指针,因为每次加入列表是新开辟的节点,只能比较坐标  
    for(auto p:list)  
        if(p->x==point->x&&p->y==point->y)  
            return p;  
    return NULL;  
}  
  
bool Astar::isCanreach(const Point *point,const Point *target,bool isIgnoreCorner) const  
{  
    if(target->x<0||target->x>maze.size()-1  
        ||target->y<0&&target->y>maze[0].size()-1  
        ||maze[target->x][target->y]==1  
        ||target->x==point->x&&target->y==point->y  
        ||isInList(closeList,target)) //如果点与当前节点重合、超出地图、是障碍物、或者在关闭列表中,返回false  
        return false;  
    else  
    {  
        if(abs(point->x-target->x)+abs(point->y-target->y)==1) //非斜角可以  
            return true;  
        else  
        {  
            //斜对角要判断是否绊住  
            if(maze[point->x][target->y]==0&&maze[target->x][point->y]==0)  
                return true;  
            else  
                return isIgnoreCorner;  
        }  
    }  
}  
  
std::vector<Point *> Astar::getSurroundPoints(const Point *point,bool isIgnoreCorner) const  
{  
    std::vector<Point *> surroundPoints;  
  
    for(int x=point->x-1;x<=point->x+1;x++)  
        for(int y=point->y-1;y<=point->y+1;y++)  
            if(isCanreach(point,new Point(x,y),isIgnoreCorner))  
                surroundPoints.push_back(new Point(x,y));  
      
    return surroundPoints;  
}

#include <math.h>
#include "Astar.h"

void Astar::InitAstar(std::vector<std::vector<int>> &_maze)
{
	maze=_maze;
}

int Astar::calcG(Point *temp_start,Point *point)
{
	int extraG=(abs(point->x-temp_start->x)+abs(point->y-temp_start->y))==1?kCost1:kCost2;
	int parentG=point->parent==NULL?0:point->parent->G; //如果是初始节点,则其父节点是空
	return parentG+extraG;
}

int Astar::calcH(Point *point,Point *end)
{
	//用简单的欧几里得距离计算H,这个H的计算是关键,还有很多算法,没深入研究^_^
	return sqrt((double)(end->x-point->x)*(double)(end->x-point->x)+(double)(end->y-point->y)*(double)(end->y-point->y))*kCost1;
}

int Astar::calcF(Point *point)
{
	return point->G+point->H;
}

Point *Astar::getLeastFpoint()
{
	if(!openList.empty())
	{
		auto resPoint=openList.front();
		for(auto &point:openList)
			if(point->F<resPoint->F)
				resPoint=point;
		return resPoint;
	}
	return NULL;
}

Point *Astar::findPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner)
{
	openList.push_back(new Point(startPoint.x,startPoint.y)); //置入起点,拷贝开辟一个节点,内外隔离
	while(!openList.empty())
	{
		auto curPoint=getLeastFpoint(); //找到F值最小的点
		openList.remove(curPoint); //从开启列表中删除
		closeList.push_back(curPoint); //放到关闭列表
		//1,找到当前周围八个格中可以通过的格子
		auto surroundPoints=getSurroundPoints(curPoint,isIgnoreCorner);
		for(auto &target:surroundPoints)
		{
			//2,对某一个格子,如果它不在开启列表中,加入到开启列表,设置当前格为其父节点,计算F G H
			if(!isInList(openList,target))
			{
				target->parent=curPoint;

				target->G=calcG(curPoint,target);
				target->H=calcH(target,&endPoint);
				target->F=calcF(target);

				openList.push_back(target);
			}
			//3,对某一个格子,它在开启列表中,计算G值, 如果比原来的大, 就什么都不做, 否则设置它的父节点为当前点,并更新G和F
			else
			{
				int tempG=calcG(curPoint,target);
				if(tempG<target->G)
				{
					target->parent=curPoint;

					target->G=tempG;
					target->F=calcF(target);
				}
			}
			Point *resPoint=isInList(openList,&endPoint);
			if(resPoint)
				return resPoint; //返回列表里的节点指针,不要用原来传入的endpoint指针,因为发生了深拷贝
		}
	}

	return NULL;
}

std::list<Point *> Astar::GetPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner)
{
	Point *result=findPath(startPoint,endPoint,isIgnoreCorner);
	std::list<Point *> path;
	//返回路径,如果没找到路径,返回空链表
	while(result)
	{
		path.push_front(result);
		result=result->parent;
	}
	return path;
}

Point *Astar::isInList(const std::list<Point *> &list,const Point *point) const
{
	//判断某个节点是否在列表中,这里不能比较指针,因为每次加入列表是新开辟的节点,只能比较坐标
	for(auto p:list)
		if(p->x==point->x&&p->y==point->y)
			return p;
	return NULL;
}

bool Astar::isCanreach(const Point *point,const Point *target,bool isIgnoreCorner) const
{
	if(target->x<0||target->x>maze.size()-1
		||target->y<0&&target->y>maze[0].size()-1
		||maze[target->x][target->y]==1
		||target->x==point->x&&target->y==point->y
		||isInList(closeList,target)) //如果点与当前节点重合、超出地图、是障碍物、或者在关闭列表中,返回false
		return false;
	else
	{
		if(abs(point->x-target->x)+abs(point->y-target->y)==1) //非斜角可以
			return true;
		else
		{
			//斜对角要判断是否绊住
			if(maze[point->x][target->y]==0&&maze[target->x][point->y]==0)
				return true;
			else
				return isIgnoreCorner;
		}
	}
}

std::vector<Point *> Astar::getSurroundPoints(const Point *point,bool isIgnoreCorner) const
{
	std::vector<Point *> surroundPoints;

	for(int x=point->x-1;x<=point->x+1;x++)
		for(int y=point->y-1;y<=point->y+1;y++)
			if(isCanreach(point,new Point(x,y),isIgnoreCorner))
				surroundPoints.push_back(new Point(x,y));
	
	return surroundPoints;
}

main.cpp
#include <iostream>  
#include "Astar.h"  
using namespace std;  
  
int main()  
{  
    //初始化地图,用二维矩阵代表地图,1表示障碍物,0表示可通  
    vector<vector<int>> maze={  
        {1,1,1,1,1,1,1,1,1,1,1,1},  
        {1,0,0,1,1,0,1,0,0,0,0,1},  
        {1,0,0,1,1,0,0,0,0,0,0,1},  
        {1,0,0,0,0,0,1,0,0,1,1,1},  
        {1,1,1,0,0,0,0,0,1,1,0,1},  
        {1,1,0,1,0,0,0,0,0,0,0,1},  
        {1,0,1,0,0,0,0,1,0,0,0,1},  
        {1,1,1,1,1,1,1,1,1,1,1,1}  
    };  
    Astar astar;  
    astar.InitAstar(maze);  
  
    //设置起始和结束点  
    Point start(1,1);  
    Point end(6,10);  
    //A*算法找寻路径  
    list<Point *> path=astar.GetPath(start,end,false);  
    //打印  
    for(auto &p:path)  
        cout<<'('<<p->x<<','<<p->y<<')'<<endl;  
  
    system("pause");  
    return 0;  
}

#include <iostream>
#include "Astar.h"
using namespace std;

int main()
{
	//初始化地图,用二维矩阵代表地图,1表示障碍物,0表示可通
	vector<vector<int>> maze={
		{1,1,1,1,1,1,1,1,1,1,1,1},
		{1,0,0,1,1,0,1,0,0,0,0,1},
		{1,0,0,1,1,0,0,0,0,0,0,1},
		{1,0,0,0,0,0,1,0,0,1,1,1},
		{1,1,1,0,0,0,0,0,1,1,0,1},
		{1,1,0,1,0,0,0,0,0,0,0,1},
		{1,0,1,0,0,0,0,1,0,0,0,1},
		{1,1,1,1,1,1,1,1,1,1,1,1}
	};
	Astar astar;
	astar.InitAstar(maze);

	//设置起始和结束点
	Point start(1,1);
	Point end(6,10);
	//A*算法找寻路径
	list<Point *> path=astar.GetPath(start,end,false);
	//打印
	for(auto &p:path)
		cout<<'('<<p->x<<','<<p->y<<')'<<endl;

	system("pause");
	return 0;
}

运行结果
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值