connected_components.h
Go to the documentation of this file.
1 /*
2  * This file is part of the alglib project.
3  *
4  * (c) Divyanshu Kakwani <divkakwani@gmail.com>
5  *
6  * For the full copyright and license information, please view the LICENSE file
7  * that was distributed with this source code.
8  */
9 
10 #pragma once
11 
13 #include <alglib/graph/dfs.h>
14 #include <vector>
15 
16 namespace alglib {
17 namespace graph {
18 
19 template<typename GraphType>
21  /* initialize each property with -1, indicating its component has not been ascertained */
22  vertex_property<GraphType, int> component_id(G, -1);
23 
24  /* start labelling component id with 1 */
25  int next_component_id = 1;
26 
27  for(auto it = G.vbegin(); it != G.vend(); it++) {
28  /* for every vertex which is not assigned a component id */
29  if(component_id(*it) == -1) {
30  std::vector<typename GraphType::vertex_type> component;
31  single_preorder_dfs(G, *it, back_inserter(component));
32 
33  /* set the component_id of each of the vertices in component */
34  for(auto vertex : component)
35  if(component_id(vertex) == -1)
36  component_id[vertex] = next_component_id;
37 
38  next_component_id++;
39  }
40  }
41  return component_id;
42 };
43 
44 } // end of graph namespace
45 } // end of alglib namespace
46 
Definition: graph_property.h:20
Definition: bimap.h:17
vertex_property< GraphType, int > connected_components(const GraphType &G)
Definition: connected_components.h:20
OutputIter single_preorder_dfs(const GraphType &G, const typename GraphType::vertex_type &start, OutputIter dest)
Definition: dfs.h:41