使用边缘容器来增强astar_search

时间:2013-11-05 00:18:59

标签: c++ boost graph a-star

我正在开发一个SFML / C ++项目,我对boost图库有一些麻烦,特别是astar_search。我为随机地图和图形生成了一个Voronoi图,使用了Boost图库的astar方法和多边形中心的中间

建立边缘:

for (Polygon *u : this->_map->_polygons)
{
    if (u->getPolygonType() == u->GROUND)
    {
        WayPointID wpID = boost::add_vertex(graphe); 
        graphe[wpID].pos = u->getCenter();
        for (std::deque<Edge_ *>::iterator it = u->getEdges().begin() ; it != u->getEdges().end() ; ++it)
        {
            std::pair<Polygon *, Polygon *> t = (*it)->_polygonsOwn;
            WayPointID wpID2 = boost::add_vertex(graphe);

            graphe[wpID2].pos = t.second->getCenter();
            if (t.first->getPolygonType() == t.first->GROUND)
            {
                float dx = abs(graphe[wpID].pos.first - graphe[wpID2].pos.first);
                float dy = abs(graphe[wpID].pos.second - graphe[wpID2].pos.second);

                boost::add_edge(wpID, wpID2, WayPointConnection(sqrt(dx * dx + dy * dy)), graphe);              
            }

当我想绘制它们时,边缘是正确建立的:

enter image description here

所以我需要使用这些边缘的astar搜索,但我的代码不起作用:(

struct found_goal {}; 
class astar_goal_visitor : public boost::default_astar_visitor{
private:
typedef boost::adjacency_list<  
    boost::listS,              
    boost::vecS,                
    boost::undirectedS,         
    WayPoint,                   
    WayPointConnection          
> WayPointGraph;
typedef WayPointGraph::vertex_descriptor WayPointID;
typedef WayPointGraph::edge_descriptor   WayPointConnectionID;
WayPointGraph graphe;
WayPointID m_goal;

public:
    astar_goal_visitor(WayPointID goal) : m_goal(goal) {}

void examine_vertex(WayPointID u, const WayPointGraph &amp){ 
    if(u == m_goal)
        throw found_goal(); 
    }

};

实施:

boost::mt19937 gen(time(0));

std::vector<WayPointID> p(boost::num_vertices(graphe)); 
std::vector<float>      d(boost::num_vertices(graphe)); 
WayPointID start = boost::random_vertex(graphe, gen);
WayPointID goal = boost::random_vertex(graphe, gen);

try {
    boost::astar_search
        (
        graphe, 
        start,  
        boost::astar_heuristic<WayPointGraph, float>(), 
                     boost::predecessor_map(&p[0]).distance_map(&d[0]).visitor(astar_goal_visitor(goal)).weight_map(boost::get(&WayPointConnection::dist, graphe))
        );

} catch(found_goal fg) { 
    std::cout << "is ok" << std::endl; 
}

永远找不到路径......如果你可以帮助我解决这个问题,我会很感激:)/ 对于这篇文章的篇幅我很抱歉:(,提升astar需要很多代码实现。

提前谢谢

1 个答案:

答案 0 :(得分:1)

插入太多顶点。你应该保留unordred_map<Polygon*,vertex_descriptor>。在为给定的多边形P调用add_vertex之前,首先应检查P是否已经在地图中。如果是,请使用与P对应的vertex_descriptor,不要调用add_vertex。否则,调用v = add_vertex并将对(P,v)添加到地图中。 祝你好运!