2

速度の理由から Astar に切り替えたいプロジェクトがあります。

しかし、C++ は私の得意分野ではありません。アルゴリズムを Dijkstra から Astar に変換するのを手伝ってくれる人はいますか (または、その方法を教えてください)。

この Astar 実装を見つけました: http://code.google.com/p/a-star-algorithm-implementation/

しかし、既存のコードでそれを使用する方法がわかりません。

アルゴリズムを取得したグラフ ファイルは次のとおりです。

#include "Graph.h"
#include <iostream>
#include <algorithm>
#include <stack>

Graph::Graph(void)
{
}

Graph::~Graph(void)
{
    while(!mNodes.empty())
    {
        delete mNodes.back();
        mNodes.pop_back();
    }
}

void Graph::addNode(int name, bool exists, Node** NodeID )
{
    Node* pStart = NULL;
    mNodes.push_back(new Node(name,exists));
    std::vector<Node*>::iterator itr;
    itr = mNodes.begin()+mNodes.size()-1;
    pStart = (*itr);
    if(exists == true)pStart->DoesExist_yes();
    *NodeID = pStart;
}

void Graph::connect_oneway(Node* pFirst, Node* pSecond, int moveCost)
{
    if(pFirst != NULL && pSecond != NULL)
    {
        pFirst->createEdge(pSecond, moveCost);
    }
}

#define MAX_NODES (32768)
#define MAX_CONNECTIONS (5)
#include <time.h>

int * Graph::findPath_r(Node* pStart, Node* pEnd)
{
    int *arr = new int[MAX_NODES+2];

    for (int i=0; i<MAX_NODES; i++)
        arr[i] = -1;

    arr[0] = 0;
    if(pStart == pEnd)
    {
        return arr;
    }

    std::vector<Node*> openList;
    openList.push_back(pStart);
    Node* pCurrNode = NULL;


    while(!openList.empty())
    {
        //Get best node from open list (lowest F value).
        //Since we sort the list at the end of the previous loop we know
        //the front node is the best
        pCurrNode = openList.front();

        //Exit if we're are the goal
        if(pCurrNode == pEnd)
            break;

        //Remove the node from the open list and place it in the closed
        openList.erase(openList.begin());
        pCurrNode->setClosed(true); //We use a flag instead of a list for speed
        //Test all of the edge nodes from the current node
        std::vector<Edge*>* pEdges = pCurrNode->getEdges();
        Node* pEdgeNode = NULL;
        for(std::vector<Edge*>::iterator i = pEdges->begin(); i != pEdges->end(); ++i)
        {
            pEdgeNode = (*i)->pNode;
            //If it's closed we've already analysed it
            if(!pEdgeNode->getClosed() && pCurrNode->DoesExist() == true)
            {
                if(!inList(pEdgeNode,&openList))
                {
                    openList.push_back(pEdgeNode);
                    pEdgeNode->setGCost(pCurrNode->getGCost()+(*i)->moveCost);
                    pEdgeNode->calcFCost();
                    pEdgeNode->setParent(pCurrNode);
                }
                else
                {
                    //If this is a better node (lower G cost)
                    if(pEdgeNode->getGCost() > pCurrNode->getGCost()+(*i)->moveCost)
                    {
                        pEdgeNode->setGCost(pCurrNode->getGCost()+(*i)->moveCost);
                        pEdgeNode->calcFCost();
                        pEdgeNode->setParent(pCurrNode);
                    }
                }
            }
        }
        //Place the lowest F cost item in the open list at the top, so we can
        //access it easily next iteration
        std::sort(openList.begin(), openList.end(),  Graph::compareNodes);
    }
    //Make sure we actually found a path
    if(pEnd->getParent() != NULL)
    {
        //Output the path
        //Use a stack because it is LIFO
        std::stack<Node*> path;
        while(pCurrNode != NULL)
        {
            path.push(pCurrNode);
            pCurrNode = pCurrNode->getParent();
        }

        int counter = 0;
        arr[1] = 0;
        while(!path.empty())
        {
            arr[counter+2] = path.top()->getName();
            counter++;
            arr[1] += path.top()->getGCost();
            path.pop();
        }
        arr[0] = counter;
        return arr;
    }
    return arr;
}

bool Graph::inList(Node* pNode, std::vector<Node*>* pList)
{
    for(std::vector<Node*>::iterator i = pList->begin(); i != pList->end(); ++i)
    {
        if((*i) == pNode)
        {
            return true;
        }
    }

    return false;
}

bool Graph::compareNodes(Node* pFirst, Node* pSecond)
{
    return pFirst->getFCost() < pSecond->getFCost();
}

void Graph::reset(void)
{
    for(std::vector<Node*>::iterator i = mNodes.begin(); i != mNodes.end(); ++i)
    {
        (*i)->reset();
    }
}

パスを見つけるための関数は次のとおりです: Graph::findPath_r

私が本当にやりたいのは、エッジを保持することです (道路が双方向か一方通行かを決定するため)。

他のファイルは次のとおりです。 Graph.h

#ifndef _GRAPH_H_
#define _GRAPH_H

#include "Node.h"

class Graph
{
public:
    Graph(void);
    ~Graph(void);

    //void addNode(int name, bool exists);
    void addNode(int name, bool exists, Node** NodeID );
    void connect_oneway(int ppFirst, int ppSecond, int moveCost);
    void connect_oneway(Node* pFirst, Node* pSecond, int moveCost);
    //int * findPath_r(int start, int end);
    int * findPath_r(Node* pStart, Node* pEnd);
    void reset(void);
private:
    void findNodesx(int firstName, Node** ppFirstNode);
    bool inList(Node* pNode, std::vector<Node*>* pList);
    static bool compareNodes(Node* pFirst, Node* pSecond);
    std::vector<Node*> mNodes;
};

#endif

Node.h

#ifndef _NODE_H_
#define _NODE_H_

#include <string>
#include <vector>

//Forward declare Node so Edge can see it
class Node;

struct Edge
{
    Edge(Node* node, int cost) : pNode(node), moveCost(cost){}
    Node* pNode;
    int moveCost;
};

class Node
{
public:
    Node(void);
    Node(int name, bool exists);
    ~Node(void);

    void createEdge(Node* pTarget, int moveCost);

    void setGCost(int cost);
    void setClosed(bool closed);
    void setParent(Node* pParent);

    int getGCost(void);
    int getFCost(void);
    bool getClosed(void);
    Node* getParent(void);
    int getName(void);
    bool DoesExist(void);
    bool DoesExist_yes(void);
    std::vector<Edge*>* getEdges(void);

    void calcFCost(void);
    void reset(void);
private:
    int mGCost;
    int mTotal;
    bool mClosed;
    Node* mpParent;
    int mName;
    bool mHeur;
    std::vector<Edge*> mEdges;
};

#endif

Node.cpp

#include "Node.h"

Node::Node(void)
{
}

Node::Node(/*const std::string&*/int name, bool exists) : mGCost(0), mTotal(0), mClosed(false), mpParent(NULL), mName(name), mHeur(exists)
{
}

Node::~Node(void)
{
    while(!mEdges.empty())
    {
        delete mEdges.back();
        mEdges.pop_back();
    }
}

int Node::getName(void)
{
    return mName;
}

void Node::createEdge(Node* pTarget, int moveCost)
{
    mEdges.push_back(new Edge(pTarget, moveCost));
}

void Node::setClosed(bool closed)
{
    mClosed = closed;
}

bool Node::getClosed(void)
{
    return mClosed;
}

std::vector<Edge*>* Node::getEdges(void)
{
    return &mEdges;
}

int Node::getGCost(void)
{
    return mGCost;
}

void Node::setGCost(int cost)
{
    mGCost = cost;
}

void Node::calcFCost(void)
{
    mTotal = mGCost;
}

void Node::setParent(Node* pParent)
{
    mpParent = pParent;
}

int Node::getFCost(void)
{
    return mTotal;
}

bool Node::DoesExist(void)
{
    return mHeur;
}

bool Node::DoesExist_yes(void)
{
    mHeur = true;
    return true;
}

Node* Node::getParent(void)
{
    return mpParent;
}

void Node::reset(void)
{
    mGCost = 0;
    mTotal = 0;
    mClosed = false;
    mpParent = NULL;
}
4

1 に答える 1

4

GoogleCode のライブラリについて言及しました。何をしたいのかは明確なノードであり、実装を自分で作成するのが最善だと思います。

まず、Dijsktra は A* の特殊なケースであることを知っておく必要があります。A* には、 hという名前のヒューリスティックがあります。A* = hが null 関数の場合の Dijsktra の可能な実装。

次に、実装について、 から始めましょうNode。次の機能が必要です。

constructor, destructor
create/get edge
set/get parent
set/is closed (for speed)
set/get GCost
set/get FCost
set/is obstacle (name way more descriptive than 'DoesExist')
set/get position
reset

// optional method:
get name

コードのこの部分があまり変わらないことを願っています。ヒューリスティック コードはパスファインダーに配置されます。Edgeクラスはそのままです。

今、大きなもの: Graph. パブリック メソッドを削除する必要はありません。

ヒューリスティックな方法が必要になります。説明する実装では、許容できる一貫したヒューリスティックが必要になります。

  • ゴールまでの距離を過大評価してはならない (許容)
  • 単調でなければならない(一貫性がある)

一般的なケースの署名はint getHCost(Node* node);. 常に 0 を返すと、ダイスクトラ アルゴリズムになりますが、これは望ましくありません。ここでは、ノードとゴールの間のユークリッド距離をとります。マンハッタン距離よりも計算が遅くなりますが、より良い結果が得られます。これは後で変更できます。

int getHCost(Node* node, Note* goal);

これは、ノードを 3D 空間に配置する必要があることを意味します。ヒューリスティックはヒューリスティック、つまり距離の推定であることに注意してください。

コードは書きません。あなたの状況に合わせた疑似コードを書きます。元の疑似コードは、ウィキペディアの A* ページにあります。この疑似コードはあなたのfindPath_r関数です:

function A*(start,goal)
    set all nodes to not closed // The set of nodes already evaluated.
    openset = {start}    // The set of tentative nodes to be evaluated, initially containing the start node

    start.gcost = 0    // Cost from start along best known path.
    // Estimated total cost from start to goal through y.
    start.fcost = start.gcost + getHCost(start, goal)

    while openset is not empty
        current = the node in openset having the lowest f_cost (usually the first if you use a sorted list)
        if current == goal
            return construct_path(goal)

        remove current from openset
        current.closed = true
        for each neighbor in (node connected by edge in current.edges) // Here is the condition for one-way edges
            if neighbor.closed or neighbor.obstacle
                continue

            gcost = current.gcost + dist_between(current,neighbor) // via edge distance

            if neighbor not in openset
                add neighbor to openset
                neighbor.parent = current
                neighbor.gcost = gcost
                neighbor.fcost = neighbor.gcost + getHCost(neighbor, goal)
            else if gcost < neighbor.gcost
                neighbor.parent = current
                neighbor.gcost = gcost
                neighbor.fcost = neighbor.gcost + getHCost(neighbor, goal)
                update neighbor position in openset

    return failure

function construct_path(current_node)
    std::vector<Node*> path
    while current_node != 0
        path.push_front(current_node)
        current_node = current_node.parent
    return path

上記の実装では、一方向エッジを使用しています。

Dijsktra アルゴリズムは C++ で記述できたので、この疑似コードを C++ で記述しても問題ありません。

第二部、公演。まず、測定します;)。

パフォーマンスを向上させるヒントがいくつかあります。

  • 割り当て解除にメモリ プールを使用する
  • 開いているリストに押し付けがましいリストを使用する (この手法で自動ソートすることもできます)

タイルマップを使用しない場合でも、役に立つ読み物であるA* for Beginnersを読むことをお勧めします。

于 2012-07-07T10:42:58.980 に答える