KrisLibrary  1.0.0
ConnectedComponents.h
1 #ifndef GRAPH_CONNECTED_COMPONENTS_H
2 #define GRAPH_CONNECTED_COMPONENTS_H
3 
4 #include "UndirectedGraph.h"
5 #include <KrisLibrary/utils/unionfind.h>
6 
7 namespace Graph {
8 
10 {
11  public:
12  template <class Node,class Edge>
13  void Compute(const UndirectedGraph<Node,Edge>& G) {
14  sets.Initialize(G.nodes.size());
15  for(size_t i=0;i<G.nodes.size();i++) {
16  for(typename Graph<Node,Edge>::ConstEdgeIterator e=G.edges[i].begin();e!=G.edges[i].end();++e) {
17  sets.Union(i,e->first);
18  }
19  }
20  }
21  void Resize(int numNodes) { sets.Initialize(numNodes); }
22  void Clear() { Resize(0); }
23  void AddEdge(int i,int j) { sets.Union(i,j); }
24  void AddNode() { sets.AddEntry(); }
25  int GetComponent(int i) { return sets.FindSet(i); }
26  int GetComponent(int i) const { return sets.FindRoot(i); }
27  bool SameComponent(int i,int j) { return sets.FindSet(i)==sets.FindSet(j); }
28  bool SameComponent(int i,int j) const { return sets.FindRoot(i)==sets.FindRoot(j); }
29  void GetRepresentatives(std::vector<int>& reps) const { sets.GetRoots(reps); }
30  size_t NumComponents() const { return sets.CountSets(); }
31  void EnumerateComponent(int node,std::vector<int>& items) const { return sets.EnumerateSet(node,items); }
32 
33  UnionFind sets;
34 };
35 
36 } //namespace Graph
37 
38 #endif
From an indexed set of elments, allows fast unioning of the elements into sets.
Definition: unionfind.h:18
Definition: ConnectedComponents.h:9
void GetRoots(std::vector< int > &roots) const
Returns the roots of all sets.
Definition: unionfind.cpp:66
size_t CountSets() const
Counts the number of sets.
Definition: unionfind.cpp:58
void EnumerateSet(int i, std::vector< int > &s) const
Returns the entire set for item i.
Definition: unionfind.cpp:86
int AddEntry()
Increment the size of X by 1, sets Sn={xn}.
Definition: unionfind.cpp:20
Namespace for all classes and functions in the Graph subdirectory.
Definition: ApproximateShortestPaths.h:7
int Union(const int i, const int j)
Unions the sets to which xi and xj belong.
Definition: unionfind.cpp:34
int FindSet(const int i)
Returns the id of the set to which xi belongs.
Definition: unionfind.cpp:26
Basic template graph structure.
Definition: Graph.h:47
void Initialize(const int entries)
Resize X to size entries, sets all sets Si={xi}.
Definition: unionfind.cpp:9
A specialization of a Graph to be an undirected graph.
Definition: UndirectedGraph.h:17