簡體   English   中英

使用Boost Graph Library(BGL)識別連接的組件

[英]Using Boost Graph Library (BGL) to identify connected components

我正在嘗試使用Boost Ggraph庫。 在我的程序的每次迭代中,我有一組點,例如{1,2,3,4,5,6,7,8,9,10}在迭代1和{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 << " ";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM