C++ Reference

C++ Reference: Graph

connected_components.h
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 //
15 // Licensed under the Apache License, Version 2.0 (the "License");
16 // you may not use this file except in compliance with the License.
17 // You may obtain a copy of the License at
18 //
19 // http://www.apache.org/licenses/LICENSE-2.0
20 //
21 // Unless required by applicable law or agreed to in writing, software
22 // distributed under the License is distributed on an "AS IS" BASIS,
23 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24 // See the License for the specific language governing permissions and
25 // limitations under the License.
26 
27 // Finds the connected components in an undirected graph:
28 // https://en.wikipedia.org/wiki/Connected_component_(graph_theory)
29 //
30 // If you have a fixed graph where the node are dense integers, use
31 // GetConnectedComponents(): it's very fast and uses little memory.
32 //
33 // If you have a more dynamic scenario where you want to incrementally
34 // add nodes or edges and query the connectivity between them, use the
35 // [Dense]ConnectedComponentsFinder class, which uses the union-find algorithm
36 // aka disjoint sets: https://en.wikipedia.org/wiki/Disjoint-set_data_structure.
37 
38 #ifndef UTIL_GRAPH_CONNECTED_COMPONENTS_H_
39 #define UTIL_GRAPH_CONNECTED_COMPONENTS_H_
40 
41 #include <functional>
42 #include <map>
43 #include <memory>
44 #include <set>
45 #include <type_traits>
46 #include <vector>
47 
48 #include "absl/container/flat_hash_map.h"
49 #include "absl/container/flat_hash_set.h"
50 #include "absl/hash/hash.h"
51 #include "absl/meta/type_traits.h"
52 #include "ortools/base/logging.h"
53 #include "ortools/base/map_util.h"
54 #include "ortools/base/ptr_util.h"
55 
56 namespace util {
57 // Finds the connected components of the graph, using BFS internally.
58 // Works on any *undirected* graph class whose nodes are dense integers and that
59 // supports the [] operator for adjacency lists: graph[x] must be an integer
60 // container listing the nodes that are adjacent to node #x.
61 // Example: std::vector<std::vector<int>>.
62 //
63 // "Undirected" means that for all y in graph[x], x is in graph[y].
64 //
65 // Returns the mapping from node to component index. The component indices are
66 // deterministic: Component #0 will be the one that has node #0, component #1
67 // the one that has the lowest-index node that isn't in component #0, and so on.
68 //
69 // Example on the following 6-node graph: 5--3--0--1 2--4
70 // vector<vector<int>> graph = {{1, 3}, {0}, {4}, {0, 5}, {2}, {3}};
71 // GetConnectedComponents(graph); // returns [0, 0, 1, 0, 1, 0].
72 template <class UndirectedGraph>
73 std::vector<int> GetConnectedComponents(int num_nodes,
74  const UndirectedGraph& graph);
75 } // namespace util
76 
77 // NOTE(user): The rest of the functions below should also be in namespace
78 // util, but for historical reasons it hasn't been done yet.
79 
80 // A connected components finder that only works on dense ints.
82  public:
84 
86  delete;
88  const DenseConnectedComponentsFinder&) = delete;
89 
90  // The main API is the same as ConnectedComponentsFinder (below): see the
91  // homonymous functions there.
92  void AddEdge(int node1, int node2);
93  bool Connected(int node1, int node2);
94  int GetSize(int node);
95  int GetNumberOfComponents() const { return num_components_; }
96  int GetNumberOfNodes() const { return parent_.size(); }
97 
98  // Sets the number of nodes in the graph. The graph can only grow: this
99  // dies if "num_nodes" is lower or equal to any of the values ever given
100  // to AddEdge(), or lower than a previous value given to SetNumberOfNodes().
101  // You need this if there are nodes that don't have any edges.
102  void SetNumberOfNodes(int num_nodes);
103 
104  // Returns the root of the set for the given node. node must be in
105  // [0;GetNumberOfNodes()-1].
106  // Non-const because it does path compression internally.
107  int FindRoot(int node);
108 
109  // Returns the same as GetConnectedComponents().
110  std::vector<int> GetComponentIds();
111 
112  private:
113  // parent[i] is the id of an ancestor for node i. A node is a root iff
114  // parent[i] == i.
115  std::vector<int> parent_;
116  // If i is a root, component_size_[i] is the number of elements in the
117  // component. If i is not a root, component_size_[i] is meaningless.
118  std::vector<int> component_size_;
119  // rank[i] is the depth of the tree.
120  std::vector<int> rank_;
121  // Number of connected components.
122  int num_components_ = 0;
123 };
124 
125 namespace internal {
126 // A helper to deduce the type of map to use depending on whether CompareOrHashT
127 // is a comparator or a hasher (prefer the latter).
128 template <typename T, typename CompareOrHashT>
130  // SFINAE trait to detect hash functors and select unordered containers if so,
131  // and ordered containers otherwise (= by default).
132  template <typename U, typename E = void>
134  using Set = std::set<T, CompareOrHashT>;
135  using Map = std::map<T, int, CompareOrHashT>;
136  };
137 
138  // The expression inside decltype is basically saying that "H(x)" is
139  // well-formed, where H is an instance of U and x is an instance of T, and is
140  // a value of integral type. That is, we are "duck-typing" on whether U looks
141  // like a hash functor.
142  template <typename U>
144  U, absl::enable_if_t<std::is_integral<decltype(
145  std::declval<const U&>()(std::declval<const T&>()))>::value>> {
146  using Set = absl::flat_hash_set<T, CompareOrHashT>;
147  using Map = absl::flat_hash_map<T, int, CompareOrHashT>;
148  };
149 
152 };
153 
154 } // namespace internal
155 
156 // Usage:
157 // ConnectedComponentsFinder<MyNodeType> cc;
158 // cc.AddNode(node1);
159 // cc.AddNode(node2);
160 // cc.AddEdge(node1, node2);
161 // ... repeating, adding nodes and edges as needed. Adding an edge
162 // will automatically also add the two nodes at its ends, if they
163 // haven't already been added.
164 // vector<set<MyNodeType> > components;
165 // cc.FindConnectedComponents(&components);
166 // Each entry in components now contains all the nodes in a single
167 // connected component.
168 //
169 // Usage with flat_hash_set:
170 // using ConnectedComponentType = flat_hash_set<MyNodeType>;
171 // ConnectedComponentsFinder<ConnectedComponentType::key_type,
172 // ConnectedComponentType::hasher>
173 // cc;
174 // ...
175 // vector<ConnectedComponentType> components;
176 // cc.FindConnectedComponents(&components);
177 //
178 // If you want to, you can continue adding nodes and edges after calling
179 // FindConnectedComponents, then call it again later.
180 //
181 // If your node type isn't STL-friendly, then you can use pointers to
182 // it instead:
183 // ConnectedComponentsFinder<MySTLUnfriendlyNodeType*> cc;
184 // cc.AddNode(&node1);
185 // ... and so on...
186 // Of course, in this usage, the connected components finder retains
187 // these pointers through its lifetime (though it doesn't dereference them).
188 template <typename T, typename CompareOrHashT = std::less<T>>
190  public:
191  // Constructs a connected components finder.
193 
196  delete;
197 
198  // Adds a node in the graph. It is OK to add the same node more than
199  // once; additions after the first have no effect.
200  void AddNode(T node) { LookupOrInsertNode<true>(node); }
201 
202  // Adds an edge in the graph. Also adds both endpoint nodes as necessary.
203  // It is not an error to add the same edge twice. Self-edges are OK too.
204  void AddEdge(T node1, T node2) {
205  delegate_.AddEdge(LookupOrInsertNode<false>(node1),
206  LookupOrInsertNode<false>(node2));
207  }
208 
209  // Returns true iff both nodes are in the same connected component.
210  // Returns false if either node has not been already added with AddNode.
211  bool Connected(T node1, T node2) {
212  return delegate_.Connected(gtl::FindWithDefault(index_, node1, -1),
213  gtl::FindWithDefault(index_, node2, -1));
214  }
215 
216  // Finds the connected component containing a node, and returns the
217  // total number of nodes in that component. Returns zero iff the
218  // node has not been already added with AddNode.
219  int GetSize(T node) {
220  return delegate_.GetSize(gtl::FindWithDefault(index_, node, -1));
221  }
222 
223  // Finds all the connected components and assigns them to components.
224  // Components are ordered in the same way nodes were added, i.e. if node 'b'
225  // was added before node 'c', then either:
226  // - 'c' belongs to the same component as a node 'a' added before 'b', or
227  // - the component for 'c' comes after the one for 'b'.
228  // There are two versions:
229  // - The first one returns the result, and stores each component in a vector.
230  // This is the preferred version.
231  // - The second one populates the result, and stores each component in a set.
232  std::vector<std::vector<T>> FindConnectedComponents() {
233  const auto component_ids = delegate_.GetComponentIds();
234  std::vector<std::vector<T>> components(delegate_.GetNumberOfComponents());
235  for (const auto& elem_id : index_) {
236  components[component_ids[elem_id.second]].push_back(elem_id.first);
237  }
238  return components;
239  }
241  std::vector<typename internal::ConnectedComponentsTypeHelper<
242  T, CompareOrHashT>::Set>* components) {
243  const auto component_ids = delegate_.GetComponentIds();
244  components->clear();
245  components->resize(delegate_.GetNumberOfComponents());
246  for (const auto& elem_id : index_) {
247  components->at(component_ids[elem_id.second]).insert(elem_id.first);
248  }
249  }
250 
251  // Returns the current number of connected components.
252  // This number can change as the new nodes or edges are added.
253  int GetNumberOfComponents() const {
254  return delegate_.GetNumberOfComponents();
255  }
256 
257  // Returns the current number of added distinct nodes.
258  // This includes nodes added explicitly via the calls to AddNode() method
259  // and implicitly via the calls to AddEdge() method.
260  // Nodes that were added several times only count once.
261  int GetNumberOfNodes() const { return delegate_.GetNumberOfNodes(); }
262 
263  private:
264  // Returns the index for the given node. If the node does not exist and
265  // update_delegate is true, explicitly add the node to the delegate.
266  template <bool update_delegate>
267  int LookupOrInsertNode(T node) {
268  const auto result = index_.emplace(node, index_.size());
269  const int node_id = result.first->second;
270  if (update_delegate && result.second) {
271  // A new index was created.
272  delegate_.SetNumberOfNodes(node_id + 1);
273  }
274  return node_id;
275  }
276 
279  index_;
280 };
281 
282 // =============================================================================
283 // Implementations of the method templates
284 // =============================================================================
285 namespace util {
286 template <class UndirectedGraph>
287 std::vector<int> GetConnectedComponents(int num_nodes,
288  const UndirectedGraph& graph) {
289  std::vector<int> component_of_node(num_nodes, -1);
290  std::vector<int> bfs_queue;
291  int num_components = 0;
292  for (int src = 0; src < num_nodes; ++src) {
293  if (component_of_node[src] >= 0) continue;
294  bfs_queue.push_back(src);
295  component_of_node[src] = num_components;
296  for (int num_visited = 0; num_visited < bfs_queue.size(); ++num_visited) {
297  const int node = bfs_queue[num_visited];
298  for (const int neighbor : graph[node]) {
299  if (component_of_node[neighbor] >= 0) continue;
300  component_of_node[neighbor] = num_components;
301  bfs_queue.push_back(neighbor);
302  }
303  }
304  ++num_components;
305  bfs_queue.clear();
306  }
307  return component_of_node;
308 }
309 } // namespace util
310 
311 #endif // UTIL_GRAPH_CONNECTED_COMPONENTS_H_
int GetNumberOfComponents() const
void AddNode(T node)
std::vector< int > GetComponentIds()
int GetSize(int node)
void AddEdge(int node1, int node2)
ConnectedComponentsFinder(const ConnectedComponentsFinder &)=delete
int GetNumberOfComponents() const
typename SelectContainer< std::less< T > >::Set Set
DenseConnectedComponentsFinder()
DenseConnectedComponentsFinder(const DenseConnectedComponentsFinder &)=delete
std::set< T, CompareOrHashT > Set
typename SelectContainer< std::less< T > >::Map Map
int GetSize(T node)
int FindRoot(int node)
absl::flat_hash_set< T, CompareOrHashT > Set
int GetNumberOfNodes() const
std::vector< int > GetConnectedComponents(int num_nodes, const UndirectedGraph &graph)
void AddEdge(T node1, T node2)
void SetNumberOfNodes(int num_nodes)
bool Connected(int node1, int node2)
DenseConnectedComponentsFinder & operator=(const DenseConnectedComponentsFinder &)=delete
ConnectedComponentsFinder()
std::vector< std::vector< T > > FindConnectedComponents()
int GetNumberOfNodes() const
void FindConnectedComponents(std::vector< typename internal::ConnectedComponentsTypeHelper< T, CompareOrHashT >::Set > *components)
absl::flat_hash_map< T, int, CompareOrHashT > Map
bool Connected(T node1, T node2)
ConnectedComponentsFinder & operator=(const ConnectedComponentsFinder &)=delete
std::map< T, int, CompareOrHashT > Map