在没有0 (number_of_vertices)的BGL中有限深度搜索使用内存或时间

Limited depth search in BGL without O(number_of_vertices) used memory or time?

本文关键字:搜索 深度 时间 内存 number of vertices BGL      更新时间:2023-10-16

是否有可能在不访问,过滤,索引等图中的所有顶点的情况下,从BGL的顶点进行深度或广度优先搜索/访问一段距离?

我写的最接近的东西是(创建图0<->1<->2<->3<->4<->5,但只访问顶点0到3):

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
using namespace std;
struct custom_dfs_visitor : public boost::default_dfs_visitor {
    template < typename Vertex, typename Graph >
    void discover_vertex(const Vertex& v, const Graph& g) const {
        std::cout << v << std::endl;
    }
};
struct Terminator {
    template<class Vertex, class Graph>
    bool operator()(const Vertex& v, const Graph& g) {
        return v > 2;
    }
};
int main()
{
    typedef boost::adjacency_list<
        boost::vecS,
        boost::vecS,
        boost::undirectedS
    > Graph_T;
    Graph_T g(6);
    boost::add_edge(0, 1, g);
    boost::add_edge(1, 2, g);
    boost::add_edge(2, 3, g);
    boost::add_edge(3, 4, g);
    boost::add_edge(4, 5, g);
    std::vector<boost::default_color_type> color_map(boost::num_vertices(g));
    boost::depth_first_visit(
        g,
        boost::vertex(0, g),
        custom_dfs_visitor(),
        boost::make_iterator_property_map(
            color_map.begin(),
            boost::get(boost::vertex_index, g),
            color_map[0]
        ),
        Terminator()
    );
    return 0;
}

只打印0 1 2 3,而不是访问所有顶点,但是代码仍然需要一个和整个图一样大的彩色地图(boost::num_vertices(g))。是否有一种方法可以使搜索复杂度完全不与图中边/顶点的总数相比较?

使用捆绑的颜色是可以接受的,因为许多搜索将在图的不同部分完成,但是有可能从O(number_of_vertices)减少同一图中每个单独搜索的复杂性吗?当终结者返回true时,顶点的初始着色也将停止,但似乎已经处理好了。也许还有一个相关的问题:如果图使用的不是vecS,那么索引怎么办?在这种情况下,BFS/DFS可以不做索引吗?谢谢你的帮助。

使用捆绑属性是完成此任务的最简单方法。事实上,在每个顶点中包含颜色属性比每次dfs完成时为每个顶点创建颜色属性要好。图形类型应为

typedef boost::adjacency_list<
    boost::vecS,
    boost::vecS,
    boost::undirectedS,
    property<vertex_color_t, boost::default_color_type>
> Graph_T;

,对DFV的调用是

depth_first_visit(
    g,
    vertex(0, g),
    custom_dfs_visitor(),
    get(vertex_color_t(), g),
    Terminator()
);

使用上面的方法,在一个有100 M个顶点的图中执行有限的dfs不会增加内存消耗(占总内存的76.2%),而使用外部颜色向量时,内存使用在搜索时从76.2%增加到78.5%。