資源簡介
A*算法的C++實現,注釋詳盡,直接編譯運行
代碼片段和文件信息
#include?
#include?
#include?
#include?“math.h“
#include
using?namespace?std;
#define?kSortOpen?sort(open.begin()?open.end()MySort);
class?CPoint
{
public:
????CPoint()
????{
????????this->x?=?0;
????????this->y?=?0;
????????this->f?=?0;
????????this->g?=?0;
????????this->h?=?0;
????????this->parent?=?NULL;
????}
????CPoint(int?x?int?y)
????{
????????this->x?=?x;
????????this->y?=?y;
????????this->f?=?0;
????????this->g?=?0;
????????this->h?=?0;
????????this->parent?=?NULL;
????}
????//xy坐標
????int?x?y;
????//f?=?g?+?h?????g:從父節點到該點消耗的步數??h:估價函數,這里直接取當前點到終點所消耗的步數
????int?f?g?h;
????CPoint*?parent;
????bool?operator?==?(const?CPoint&?p)
????{
????????if?(this->x?==?p.x?&&?this->y?==?p.y)
????????{
????????????return?true;
????????}
????????return?false;
????}
????bool?operator?(const?CPoint?&p)
????{
????????if?(this->f?<=?p.f)
????????{
????????????return?true;
????????}
????????else
????????{
????????????return?false;
????????}
????}
};
struct?List
{
????CPoint*?parent?next;
};
typedef?std::vector?vecCpoint;
bool?Exsit(vecCpoint&?vec?CPoint*?p)
{
????vecCpoint::iterator?it?=?vec.begin();
????for?(;?it?!=?vec.end();?it++)
????{
????????if?((*(*it))?==?(*p))
????????{
????????????return?true;
????????}
????}
????return?false;
}
CPoint*?FindItem(vecCpoint&?vecCPoint*?p)
{
????if?(Exsit(vecp))
????{
????????vecCpoint::iterator?it?=?vec.begin();
????????for?(;?it?!=?vec.end();?it++)
????????{
????????????if?((*(*it))?==?(*p))
????????????{
????????????????return?*it;
????????????}
????????}
????????return?NULL;
????}
????return?NULL;
}
vecCpoint::iterator?FindItemIter(vecCpoint&?vecCPoint*?p)
{
????if?(Exsit(vecp))
????{
????????vecCpoint::iterator?it?=?vec.begin();
????????for?(;?it?!=?vec.end();?it++)
????????{
????????????if?((*(*it))?==?(*p))
????????????{
????????????????return?it;
????????????}
????????}
????????return?vec.end();
????}
????return?vec.end();
}
void?Score(CPoint*?beginner?CPoint*?ended?CPoint*?cur)
{
????cur->g?=?abs(beginner->x?-?cur->x)?+?abs(beginner->y?-?cur->y);
????cur->h?=?abs(ended->x?-?cur->x)?+?abs(ended->y?-?cur->y);
????cur->f?=?cur->g?+?cur->h;
//????cout?<“g?=?“?<g?<//????cout?<“h?=?“?<h?<//????cout?<“f?=?“?<f?<}
bool?FindChildren(CPoint*?first?char?map[10][10]?CPoint*?beginnerCPoint*?endedvecCpoint&?openvecCpoint&?close)
{
????bool?bValid?=?false;
????if?(first->x?-?1?>=?0?&&?map[first->x?-?1][first->y]?==?‘1‘)
????{
????????CPoint*?left?=?new?CPoint(first->x?-?1?first->y);
????????Score(beginner?ended?left);
????????if?(!Exsit(openleft)?&&?!Exsit(closeleft))
????????{
????????????left->parent?=?first;
????????????open.push_back(left);
????????????bValid?=?true;
????????}
????????else?if?(Exsit(openleft))
????????{
????????????CPoint*?old_open?=?FindItem(openleft);
????????????if?(left->f?f)
????????????{
????????????????old_open->f?=?left->f;
????????????????old_open->
- 上一篇:螞蟻算法MFC實現執行文件
- 下一篇:用I/O命令訪問PCI總線設備配置空間
評論
共有 條評論