C++ Boost

connected_components

Graphs: see below
Properties: components, color
Complexity: O(V + E)

(2)
template <class VertexListGraph, class ComponentMap, class ColorMap>
typename property_traits<ComponentMap>::value_type
connected_components(VertexListGraph& G, ComponentMap comp, ColorMap color);

(2)
template <class VertexListGraph, 
          class ComponentMap, class ColorMap, class DFSVisitor>
typename property_traits<ComponentMap>::value_type
connected_components(VertexListGraph& G, ComponentMap comp, ColorMap color,
  DFSVisitor v);

The connected_components() functions compute the connected components of an undirected graph using a DFS-based approach. If the connected-components are to be calculated over and over while a graph is changing the disjoint-set based approach of function dynamic_connected_components() is faster. For ``static'' graphs this DFS-based approach is faster [8].

The output of the algorithm is recorded in the component property map comp, which will contain numbers giving the component ID assigned to each vertex. The number of components is the return value of the function.

The algorithm requires the use of several property maps: color, discover time, and finish time. There are several versions of this algorithm to accommodate whether you wish to use interior or exterior property maps.

Where Defined

boost/graph/connected_components.hpp

Definitions

A connected component of an undirected graph is a set of vertices that are all reachable from each other.

Requirements on Types

Complexity

The time complexity for the connected components algorithm is also O(V + E).

See Also

strong_components() and incremental_components()

Example

Calculating the connected components of an undirected graph. The complete source is in file examples/connected_components.cpp.

  typedef discover_time_property< finish_time_property
                                < color_property<> > > VertexProperty;
  typedef adjacency_list <vecS, vecS, undirectedS, VertexProperty> Graph;
  typedef graph_traits<Graph>::vertex_descriptor Vertex;

  const int N = 6;
  Graph G(N);
  add_edge(0, 1, G);
  add_edge(1, 4, G);
  add_edge(4, 0, G);
  add_edge(2, 5, G);
    
  std::vector<int> c(num_vertices(G));
  int num = connected_components(G, c.begin(), 
              get_color_map(G), null_visitor());
    
  cout << endl;
  std::vector<int>::iterator i;
  cout << "Total number of components: " << num << endl;
  for (i = c.begin(); i != c.end(); ++i)
    cout << "Vertex " << i - c.begin() 
         << " is in component " << *i << endl;
  cout << endl;
The output is:
  Total number of components: 3
  Vertex 0 is in component 1
  Vertex 1 is in component 1
  Vertex 2 is in component 2
  Vertex 3 is in component 3
  Vertex 4 is in component 1
  Vertex 5 is in component 2



Copyright © 2000 Jeremy Siek, Univ.of Notre Dame (jsiek@lsc.nd.edu)