使用提升图形库 (BGL) 识别连接的组件

Using Boost Graph Library (BGL) to identify connected components

本文关键字:识别 连接 组件 BGL 图形库      更新时间:2023-10-16

我正在尝试使用Boost Ggraph库。在我的程序的每次迭代中,我都有一组点,例如迭代一上的 {1,2,3,4,5,6,7,8,9,10} 和迭代二上的 {1,2,3,...,1000},...

对于每个点,

我知道它连接到哪些其他点,例如在迭代一中,每个点都连接如下:

c(1)={3,5,7,8}   
c(2)={}   
c(3)={1,4,10}   
c(4)={3}    
c(5)={1,9}   
c(6)={}    
c(7)={1,8}    
c(8)={1,7}    
c(9)={5}    
c(10)={3}    

每个点都有一个属性,例如 p(1)=10, p(2)=100, p(3)=20, ...

如何在 Boost 中创建无向图并迭代连接的组件?

您需要包含以下标头:

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>

然后,您需要为图形声明一个类型。以下内容适用于您给出的要求,但您可能需要查阅此页面以了解有关模板参数的其他选择的更多信息:

typedef
  boost::adjacency_list<
    boost::vecS            // edge list
  , boost::vecS            // vertex list
  , boost::undirectedS     // directedness
  , float                  // property associated with vertices
  >
Graph;

您可以创建具有给定点数的图形,以后可以添加更多点:

Graph c (10);              // create a graph with 10 points
boost::add_vertex (c);     // add a vertex to the graph

要添加边,请使用(请注意,从 0 开始枚举顶点):

boost::add_edge (0, 1, c); // add an edge between vertices 0 and 1 in the graph

最后,使用以下代码段,您可以计算图形中的连接组件:

std::vector<int> component (boost::num_vertices (c));
size_t num_components = boost::connected_components (c, &component[0]);

从函数返回的值是找到的组件数。向量中的每个项目都将设置为相应顶点component组件 ID。这意味着您可以迭代它,例如打印属于特定组件的顶点:

std::cout << "Vertices in the first component:" << std::endl;
for (size_t i = 0; i < boost::num_vertices (c); ++i)
  if (component[i] == 0)
    std::cout << i << " ";