简易地图
如图所示简易地图, 其中绿色方块的是起点 (用 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 右边的方块), 然后对它进行如下处理:
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( 目标格已经在 "开启列表", 这时候路径被找到)
如果开启列表已经空了, 说明路径不存在.
最后从目标格开始, 沿着每一格的父节点移动直到回到起始格, 这就是路径.
C++实现代码:
版本1:
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class CPoint
{
public:
CPoint(int x, int y) :X(x), Y(y), m_pParentPoint(NULL), G(0), F(0), H(0)
{
}
~CPoint()
{
}
void calcF(){
this->F = this->H + this->G;
}
public:
int X;
int Y;
int G;
int H;
int F;
CPoint* m_pParentPoint;
};
bool CompF(const CPoint* pl, const CPoint* pr)
{
return pl->F < pr->F;
}
class CAstar
{
public:
CAstar(int textureMap[][12])
{
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
m_textureMap[i][j] = 0;
}
}
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 12; j++)
{
m_textureMap[i][j] = textureMap[i][j];
}
}
}
CPoint* FindPath(CPoint* start, CPoint* end, bool IsIgnoreCorner)
{
m_listOpen.push_back(start);//将起始点放到开启列表中
while (m_listOpen.size())
{
CPoint* tempStart = getMinFPoint(); //获取F值最低的点
removeFromOpenList(tempStart);//将这个店中开启列表中删除
m_listClose.push_back(tempStart);//将这个点放到关闭列表中
std::vector<CPoint*> surroundPoints = SurrroundPoints(tempStart, IsIgnoreCorner);//获取F值最低点相邻的点
tPointList::iterator _iter = surroundPoints.begin();
//遍历这些相邻点
for (_iter; _iter != surroundPoints.end(); ++_iter)
{
CPoint *point = *_iter;
if (inOpenList(point->X, point->Y))//如果这个点在开启列表中
FoundPoint(tempStart, point);//重新计算G值,如果G值更小,则更新父节点,并且重新计算F值,否则什么都不做
else
NotFoundPoint(tempStart, end, point);//不在开启列表中,则加入开启列表,计算G值,F值,设定父节点
}
if (inOpenList(end->X, end->Y))//目标结点已经在开启列表中
{
//返回在开启列表中的父节点
for (int i = 0; i < m_listOpen.size(); i++)
{
if (m_listOpen[i]->X == end->X && m_listOpen[i]->Y == end->Y)
{
return m_listOpen[i];
}
}
}
}
return end;
}
bool CanReach(int x, int y)
{
return m_textureMap[x][y] == 0;
}
bool inCloseList(int x, int y)
{
CPoint* p = new CPoint(x, y);
tPointList::iterator _iter = m_listClose.begin();
for (_iter; _iter != m_listClose.end(); ++_iter)
{
CPoint* temp = *_iter;
if (temp->X == p->X && temp->Y == p->Y)
return true;
}
if (p)
{
delete p;
p = NULL;
}
return false;
}
bool inOpenList(int x, int y)
{
CPoint *p = new CPoint(x, y);
tPointList::iterator _iter = m_listOpen.begin();
for (_iter; _iter != m_listOpen.end(); ++_iter)
{
CPoint* temp = *_iter;
if (temp->X == p->X && temp->Y == p->Y)
return true;
}
if (p)
{
delete p;
p = NULL;
}
return false;
}
bool CanReach(CPoint* start, int x, int y, bool IsIgnoreCorner)
{
if (!CanReach(x, y) || inCloseList(x, y))
return false;
else
{
if ((abs(x - start->X) + abs(y - start->Y)) == 1)
return true;
else
{
if (CanReach(abs(x - 1), y) && CanReach(x, abs(y - 1)))
return true;
else
return IsIgnoreCorner;
}
}
}
std::vector<CPoint*> SurrroundPoints(CPoint* point, bool IsIgnoreCorner)
{
tPointList surroundPoints;
for (int x = point->X - 1; x <= point->X + 1; x++)
for (int y = point->Y - 1; y <= point->Y + 1; y++)
{
if (CanReach(point, x, y, IsIgnoreCorner))
{
CPoint *p = new CPoint(x, y);
surroundPoints.push_back(p);
}
else
{
}
}
return surroundPoints;
}
CPoint* getMinFPoint()
{
tPointList tempList;
for (int i = 0; i < (int)m_listOpen.size(); i++)
{
tempList.push_back(m_listOpen[i]);
}
sort(tempList.begin(), tempList.end(), CompF);
if (tempList.size())
{
return tempList[0];
}
}
void removeFromOpenList(CPoint* point)
{
tPointList::iterator _iter = m_listOpen.begin();
for (_iter; _iter != m_listOpen.end(); ++_iter)
{
m_listOpen.erase(_iter);
break;
}
}
void FoundPoint(CPoint* tempStart, CPoint* point)
{
int G = CalcG(tempStart, point);
if (G < point->G)
{
point->m_pParentPoint = tempStart;
point->G = G;
point->calcF();
}
}
void NotFoundPoint(CPoint* tempStart, CPoint* end, CPoint* point)
{
point->m_pParentPoint = tempStart;
point->G = CalcG(tempStart, point);
point->H = CalcH(end, point);
point->calcF();
m_listOpen.push_back(point);
}
int CalcG(CPoint* start, CPoint* point)
{
int G = (abs(point->X - start->X) + abs(point->Y - start->Y)) == 2 ? STEP : OBLIQUE;
int parentG = point->m_pParentPoint != NULL ? point->m_pParentPoint->G : 0;
return G + parentG;
}
int CalcH(CPoint* end, CPoint* point)
{
int step = abs(point->X - end->X) + abs(point->Y - end->Y);
return step * STEP;
}
private:
static const int STEP = 10;
static const int OBLIQUE = 14;
typedef std::vector<CPoint*> tPointList;
tPointList m_listOpen;
tPointList m_listClose;
int m_textureMap[100][100];
};
int main(int argc, char* argv[])
{
int array[12][12] = {
{ 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 }
};
CAstar *maze = new CAstar(array);
CPoint *start = new CPoint(1, 1);
CPoint *end = new CPoint(6, 10);
CPoint* parent = maze->FindPath(start, end, false);
while (parent != NULL)
{
cout << parent->X << "," << parent->Y << endl;
parent = parent->m_pParentPoint;
}
getchar();
return 0;
}
版本2:
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; //关闭列表
};
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;
}
// 清空临时开闭列表,防止重复执行GetPath导致结果异常
openList.clear();
closeList.clear();
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;
}
版本3:
Astar.h
#ifndef ASTAR_H
#define ASTAR_H
#include <iostream>
#include <queue>
#include <vector>
#include <stack>
#include<algorithm>
using namespace std;
typedef struct Node
{
int x, y;
int g; //起始点到当前点实际代价
int h;//当前节点到目标节点最佳路径的估计代价
int f;//估计值
Node* father;
Node(int x, int y)
{
this->x = x;
this->y = y;
this->g = 0;
this->h = 0;
this->f = 0;
this->father = NULL;
}
Node(int x, int y, Node* father)
{
this->x = x;
this->y = y;
this->g = 0;
this->h = 0;
this->f = 0;
this->father = father;
}
}Node;
class Astar{
public:
Astar();
~Astar();
void search(Node* startPos, Node* endPos);
void checkPoit(int x, int y, Node* father, int g);
void NextStep(Node* currentPoint);
int isContains(vector<Node*>* Nodelist, int x, int y);
void countGHF(Node* sNode, Node* eNode, int g);
static bool compare(Node* n1, Node* n2);
bool unWalk(int x, int y);
void printPath(Node* current);
void printMap();
vector<Node*> openList;
vector<Node*> closeList;
Node *startPos;
Node *endPos;
static const int WeightW = 10;// 正方向消耗
static const int WeightWH = 14;//打斜方向的消耗
static const int row = 6;
static const int col = 8;
};
#endif
Astar.cpp
#include "Astar.h"
int map[101][101] =
{
//{ 0, 0, 0, 1, 0, 1, 0, 0, 0 },
//{ 0, 0, 0, 1, 0, 1, 0, 0, 0 },
//{ 0, 0, 0, 0, 0, 1, 0, 0, 0 },
//{ 0, 0, 0, 1, 0, 1, 0, 1, 0 },
//{ 0, 0, 0, 1, 0, 1, 0, 1, 0 },
//{ 0, 0, 0, 1, 0, 0, 0, 1, 0 },
//{ 0, 0, 0, 1, 0, 0, 0, 1, 0 }
};
Astar::Astar()
{
}
Astar::~Astar()
{
}
void Astar::search(Node* startPos, Node* endPos)
{
if (startPos->x < 0 || startPos->x > row || startPos->y < 0 || startPos->y >col ||
endPos->x < 0 || endPos->x > row || endPos->y < 0 || endPos->y > col)
return;
Node* current;
this->startPos = startPos;
this->endPos = endPos;
openList.push_back(startPos);
//主要是这块,把开始的节点放入openlist后开始查找旁边的8个节点,如果坐标超长范围或在closelist就return 如果已经存在openlist就对比当前节点到遍历到的那个节点的G值和当前节点到原来父节点的G值 如果原来的G值比较大 不用管 否则重新赋值G值 父节点 和f 如果是新节点 加入到openlist 直到opellist为空或找到终点
while (openList.size() > 0)
{
current = openList[0];
if (current->x == endPos->x && current->y == endPos->y)
{
cout << "find the path" << endl;
printMap();
printPath(current);
openList.clear();
closeList.clear();
break;
}
NextStep(current);
closeList.push_back(current);
openList.erase(openList.begin());
sort(openList.begin(), openList.end(), compare);
}
}
void Astar::checkPoit(int x, int y, Node* father, int g)
{
if (x < 0 || x > row || y < 0 || y > col)
return;
if (this->unWalk(x, y))
return;
if (isContains(&closeList, x, y) != -1)
return;
int index;
if ((index = isContains(&openList, x, y)) != -1)
{
Node *point = openList[index];
if (point->g > father->g + g)
{
point->father = father;
point->g = father->g + g;
point->f = point->g + point->h;
}
}
else
{
Node * point = new Node(x, y, father);
countGHF(point, endPos, g);
openList.push_back(point);
}
}
void Astar::NextStep(Node* current)
{
checkPoit(current->x - 1, current->y, current, WeightW);//左
checkPoit(current->x + 1, current->y, current, WeightW);//右
checkPoit(current->x, current->y + 1, current, WeightW);//上
checkPoit(current->x, current->y - 1, current, WeightW);//下
checkPoit(current->x - 1, current->y + 1, current, WeightWH);//左上
checkPoit(current->x - 1, current->y - 1, current, WeightWH);//左下
checkPoit(current->x + 1, current->y - 1, current, WeightWH);//右下
checkPoit(current->x + 1, current->y + 1, current, WeightWH);//右上
}
int Astar::isContains(vector<Node*>* Nodelist, int x, int y)
{
for (int i = 0; i < Nodelist->size(); i++)
{
if (Nodelist->at(i)->x == x && Nodelist->at(i)->y == y)
{
return i;
}
}
return -1;
}
void Astar::countGHF(Node* sNode, Node* eNode, int g)
{
int h = abs(sNode->x - eNode->x) + abs(sNode->y - eNode->y) * WeightW;
int currentg = sNode->father->g + g;
int f = currentg + h;
sNode->f = f;
sNode->h = h;
sNode->g = currentg;
}
bool Astar::compare(Node* n1, Node* n2)
{
//printf("%d,%d",n1->f,n2->f);
return n1->f < n2->f;
}
bool Astar::unWalk(int x, int y)
{
if (map[x][y] == 1)
return true;
return false;
}
void Astar::printPath(Node* current)
{
if (current->father != NULL)
printPath(current->father);
printf("(%d,%d)", current->x, current->y);
}
void Astar::printMap()
{
for (int i = 0; i <= row; i++){
for (int j = 0; j <= col; j++){
printf("%d ", map[i][j]);
}
printf("\n");
}
}
main.cpp
#include "Astar.h"
int main(int argc, char* argv[])
{
Astar astar;
Node *startPos = new Node(5, 1);
Node *endPos = new Node(3, 8);
astar.search(startPos, endPos);
getchar();
return 0;
}
版本4:
Apath,h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#ifndef APATH_H
#define APATH_H
#endif
#define TURE 1
#define FAULT 0
//约定:0是可走的,1表示障碍物不可走,2表示起点,3表示终点,4表示路径
#define int_0 0
#define int_1 1
#define int_2 2
#define int_3 3
#define int_4 4
#define MAP_MAX_X 10 //地图边界,二维数组大小
#define MAP_MAX_Y 10
typedef struct LNode {
int data; //对应数组中的数值
int F; //F = G + H;
int G; //G:从起点 A 移动到指定方格的移动代价,沿着到达该方格而生成的路径
int H; //H:从指定的方格移动到终点 B 的估算成本
int x, y; //对应数组中的坐标
bool OPen_flag; //在开放列表中为1,不在为0
bool Close_flag; //在关闭列表中为1,不在为0
struct LNode* next; //用于链表排序
struct LNode* path_next; //用于最终找到的路径
}LNode, *LinkList;
LinkList InitList(); //返回一个初始化的链表
LNode** malloc_array2D(int row, int col);
void free_array2D(LNode **arr);
LNode** Translate_array(int array[10][10], int row, int col); //将一个普通数组翻译为单链表节点的数组
void output(LNode **array, int row, int col);
LNode* find_start_LNode(LNode** Arr, int row, int col); //从数组中找到始点
LNode* find_end_LNode(LNode** Arr, int row, int col); //从数组中找到终点
//忘记这些要干嘛了,重写吧
bool isExist_ALNode_in_List(LNode* curLNode, LinkList L_OpenList); //查看节点是否在链表中,在返回ture,不在返回fault
//对关闭列表中的当前节点进行检查,看它周围的节点是否在OpenList链表里,不在:添加进去;在:检查经过它到达起点的G是否最小,是:修改,不是:不修改
//LNode* check_CloseList_curLNode(LNode* curLNode, LNode* endLNode, LinkList L_OpenList, LinkList L_CloseList, LNode** Arr);
LNode* pop_OpenList_minNode(LinkList L_OpenList); //返回开放列表中F值最小的节点
void push_OpenList_Node(LinkList L, LNode *elem); //插入一个节点并排序
bool insert_Into_CloseList(LNode* min_Open, LinkList L_CloseList);//插入OpenList中F值最小的节点到CloseList中去
int count_LNode_G(LNode* curLNode, LNode* aheadLNode); //计算节点的G值
int count_LNode_H(LNode* curLNode, LNode* endLNode); //计算节点的H值
int count_LNode_F(LNode* curLNode); //计算节点的F值
bool isExist_openList(LNode* curLNode); //查看节点是否在链表中,在返回ture,不在返回fault
bool isExist_closeList(LNode* curLNode);
bool isobstacle(LNode* curLNode);
void check_around_curNode(LNode* cur, LNode* endLNode, LinkList open_list, LNode** Arr); //检查周围的节点,是否合适加入开放列表
Apath.cpp
#include "Apath.h"
LinkList InitList()
{
LinkList L = (LinkList)malloc(sizeof(LNode));
if (L == NULL)
{
printf("Defeat!");
exit(1);
}
memset(L, 0, sizeof(LNode));
return L;
}//LinkList()
LNode** malloc_array2D(int row, int col)
{
LNode** map = (LNode**)malloc(row*sizeof(LNode*)+row*col*sizeof(LNode));
LNode* head = (LNode*)(map + row);
for (int i = 0; i < row; ++i)
map[i] = head + i*col;
return map;
}
LNode** Translate_array(int array[][10], int row, int col)
{
LNode **map = malloc_array2D(10, 10);
for (int i = 0; i < row; ++i)
for (int j = 0; j < col; ++j)
{
(map[i] + j)->data = array[i][j];
(map[i] + j)->G = 0;
(map[i] + j)->H = 0;
(map[i] + j)->F = 0; //(map[i] + j)->G + (map[i] + j)->H;
(map[i] + j)->x = i;
(map[i] + j)->y = j;
(map[i] + j)->Close_flag = 0;
(map[i] + j)->OPen_flag = 0;
(map[i] + j)->next = NULL;
(map[i] + j)->path_next = NULL;
}
return map;
}//Translate_array()
void free_array2D(LNode **arr)
{
free(arr);
}
void output(LNode** array, int row, int col) //二维数组的访问必须指明位数,否则编译器不能解析
{
//for (int i = 0; i < row; ++i)
// for (int j = 0; j < col; ++j)
// {
// (array[i] + j)->F = j;
// }
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
printf("%d\t", (array[i] + j)->data);
}
printf("\n");
}
}
LNode* find_start_LNode(LNode** Arr, int row, int col) //从数组中找到始点
{
LNode* start_LNode = NULL;
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
if (2 == (Arr[i] + j)->data)
{
start_LNode = (Arr[i] + j);
//起点H=0,G=0,F=0
start_LNode->G = 0;
start_LNode->H = 0;
start_LNode->F = 0; //起点,则默认所有值为0
return start_LNode; //返回节点
}
}
}
return NULL;
}
LNode* find_end_LNode(LNode** Arr, int row, int col) //从数组中找到终点
{
LNode* end_LNode = NULL;
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
if (3 == (Arr[i] + j)->data)
{
end_LNode = (*(Arr + i) + j);
end_LNode->F = 0;
end_LNode->G = 0;
end_LNode->H = 0;
return end_LNode; //返回节点
}
}
}
return NULL;
}
int count_LNode_G(LNode* curLNode, LNode* aheadLNode) //计算节点的G值
{
if (curLNode->x == aheadLNode->y && curLNode->y == aheadLNode->y)
return 0;
if (aheadLNode->x - curLNode->x != 0 && aheadLNode->y - curLNode->y != 0)
curLNode->G = aheadLNode->G + 14;
else
curLNode->G = aheadLNode->G + 10;
return curLNode->G;
}
int count_LNode_H(LNode* curLNode, LNode* endLNode) //计算节点的H值
{
curLNode->H = abs(endLNode->x - curLNode->x) * 10 + abs(endLNode->y - curLNode->y) * 10;
return curLNode->H;
}
int count_LNode_F(LNode* curLNode) //计算节点的F值
{
curLNode->F = curLNode->G + curLNode->H;
return curLNode->F;
}
void push_OpenList_Node(LinkList L, LNode *elem) //按从小到大的顺序
{
LNode *p, *q;
p = q = L;
while (p->next != NULL && p->F < elem->F)
{
q = p;
p = p->next;
}
if (p->F < elem->F) q = p;
elem->next = q->next;
q->next = elem;
//插入成功,更改属性值OPen_flag = 1
elem->OPen_flag = 1;
}
LNode* pop_OpenList_minNode(LinkList L_OpenList) //返回开放列表中F值最小的节点
{
LNode *elem = NULL;
if (L_OpenList->next) //为了安全,防止访问空指针
{
L_OpenList->next->OPen_flag = 0;
elem = L_OpenList->next;
L_OpenList->next = L_OpenList->next->next;
elem->next = NULL;
}
else
printf("have a NULL point in pop_OpenList_mimNode()");
return elem;
}
bool insert_Into_CloseList(LNode* min_Open, LinkList L_CloseList)//插入OpenList中F值最小的节点到CloseList中去
{
//对于CloseList中的节点并不需要排序,采用头插法
min_Open->next = L_CloseList->next;
L_CloseList->next = min_Open;
min_Open->Close_flag = 1;
return TURE;
}
bool isExist_openList(LNode* curLNode)
{
return curLNode->OPen_flag;
}
bool isExist_closeList(LNode* curLNode)
{
return curLNode->Close_flag;
}
bool isobstacle(LNode* curLNode)
{
if (curLNode->data == 1)
return TURE;
else
return FAULT;
}
bool isJoin(LNode* cur) //该节点是否可以加入开放列表
{
if (cur->x > -1 && cur->y > -1) //边界检测
{
if (!isExist_closeList(cur) && !isobstacle(cur)) //既不在关闭列表里,也不是障碍物
{
return TURE;
}
else
return FAULT;
}
return FAULT;
}
void insert_open(LNode *Node, LNode* ahead, LNode* endLNode, LinkList open_list, LNode** Arr)
{
if (isJoin(Node))
{
if (isExist_openList(Node))
{
if (Node->x - ahead->x != 0 && Node->y - ahead->y != 0) {
if (Node->F > (ahead->F + 14))
{
count_LNode_G(Node, ahead);
count_LNode_F(Node); //H值没有改变,所以还是原来的值
Node->path_next = ahead; //也不用再插入
}
}
else {
if (Node->F > (ahead->F + 10))
{
count_LNode_G(Node, ahead);
count_LNode_F(Node); //H值没有改变,所以还是原来的值
Node->path_next = ahead; //也不用再插入
}
}
}
else {
count_LNode_G(Node, ahead);
count_LNode_H(Node, endLNode);
count_LNode_F(Node);
Node->path_next = ahead;
push_OpenList_Node(open_list, Node);
}
}
}
void check_around_curNode(LNode* cur, LNode* endLNode, LinkList open_list, LNode** Arr)
{
int x = cur->x;
int y = cur->y;
insert_open(Arr[x] + y - 1, cur, endLNode, open_list, Arr);
insert_open(Arr[x] + y + 1, cur, endLNode, open_list, Arr);
insert_open(Arr[x + 1] + y, cur, endLNode, open_list, Arr);
insert_open(Arr[x + 1] + y - 1, cur, endLNode, open_list, Arr);
insert_open(Arr[x + 1] + y + 1, cur, endLNode, open_list, Arr);
insert_open(Arr[x - 1] + y, cur, endLNode, open_list, Arr);
insert_open(Arr[x - 1] + y + 1, cur, endLNode, open_list, Arr);
insert_open(Arr[x - 1] + y - 1, cur, endLNode, open_list, Arr);
}
main.cpp
#include <stdio.h>
//#ifndef APATH_H
#include "Apath.h"
//#endif
//为简单,干脆把把下面数组转为链表结构的数组
//约定:0是可走的,1表示障碍物不可走,2表示起点,3表示终点,4表示路径
int array[10][10] = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 3, 0, 0, 0 },
{ 0, 0, 2, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
int main()
{
int row = MAP_MAX_X, col = MAP_MAX_Y;
printf("hello world!\n");
LNode **map = Translate_array(array, row, col); //这里将数组的地图转为节点map的地图
output(map, 10, 10);
LinkList open_List = InitList(); //定义并初始化一个开放列表
LinkList close_List = InitList(); //一个封闭列表
LNode* startLNode = find_start_LNode(map, row, col);
LNode* endLNode = find_end_LNode(map, row, col);
LNode* curLNode = startLNode; //当前节点=开始节点
curLNode->G = 0; //计算节点的三个值
count_LNode_H(curLNode, endLNode);
count_LNode_F(curLNode);
push_OpenList_Node(open_List, curLNode); //先将开始节点插入开放列表
while (curLNode->data != 3)
{
//LNode *e = NULL;
curLNode = pop_OpenList_minNode(open_List);
insert_Into_CloseList(curLNode, close_List);
//2、查看起点周围的点是否在开放列表里,不在加入,在检测经过该点F值是否最小等;
check_around_curNode(curLNode, endLNode, open_List, map);
}
while (endLNode->path_next)
{
printf("x:%d---y:%d\n", endLNode->path_next->x, endLNode->path_next->y);
endLNode->path_next = endLNode->path_next->path_next;
}
getchar();
return 0;
}