OR-Tools  9.3
connected_components.h
Go to the documentation of this file.
1// Copyright 2010-2021 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"
55
56namespace 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].
72template <class UndirectedGraph>
73std::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
85 // We support copy and move construction.
87 default;
89 const DenseConnectedComponentsFinder&) = default;
92 default;
93
94 // The main API is the same as ConnectedComponentsFinder (below): see the
95 // homonymous functions there.
96 bool AddEdge(int node1, int node2);
97 bool Connected(int node1, int node2);
98 int GetSize(int node);
99 int GetNumberOfComponents() const { return num_components_; }
100 int GetNumberOfNodes() const { return parent_.size(); }
101
102 // Gets the current set of root nodes in sorted order. Runs in amortized
103 // O(#components) time.
104 const std::vector<int>& GetComponentRoots();
105
106 // Sets the number of nodes in the graph. The graph can only grow: this
107 // dies if "num_nodes" is lower or equal to any of the values ever given
108 // to AddEdge(), or lower than a previous value given to SetNumberOfNodes().
109 // You need this if there are nodes that don't have any edges.
110 void SetNumberOfNodes(int num_nodes);
111
112 // Returns the root of the set for the given node. node must be in
113 // [0;GetNumberOfNodes()-1].
114 // Non-const because it does path compression internally.
115 int FindRoot(int node);
116
117 // Returns the same as GetConnectedComponents().
118 std::vector<int> GetComponentIds();
119
120 private:
121 // parent[i] is the id of an ancestor for node i. A node is a root iff
122 // parent[i] == i.
123 std::vector<int> parent_;
124 // If i is a root, component_size_[i] is the number of elements in the
125 // component. If i is not a root, component_size_[i] is meaningless.
126 std::vector<int> component_size_;
127 // rank[i] is the depth of the tree.
128 std::vector<int> rank_;
129 // Number of connected components.
130 int num_components_ = 0;
131 // The current roots. This is maintained lazily by GetComponentRoots().
132 std::vector<int> roots_;
133 // The number of nodes that existed the last time GetComponentRoots() was
134 // called.
135 int num_nodes_at_last_get_roots_call_ = 0;
136};
137
138namespace internal {
139// A helper to deduce the type of map to use depending on whether CompareOrHashT
140// is a comparator or a hasher (prefer the latter).
141template <typename T, typename CompareOrHashT, typename Eq>
143 // SFINAE trait to detect hash functors and select unordered containers if so,
144 // and ordered containers otherwise (= by default).
145 template <typename U, typename V, typename E = void>
147 using Set = std::set<T, CompareOrHashT>;
148 using Map = std::map<T, int, CompareOrHashT>;
149 };
150
151 // Specialization for when U is a hash functor and Eq is void (no custom
152 // equality).
153 // The expression inside decltype is basically saying that "H(x)" is
154 // well-formed, where H is an instance of U and x is an instance of T, and is
155 // a value of integral type. That is, we are "duck-typing" on whether U looks
156 // like a hash functor.
157 template <typename U, typename V>
159 U, V,
160 absl::enable_if_t<std::is_integral<decltype(std::declval<const U&>()(
161 std::declval<const T&>()))>::value &&
162 std::is_same_v<V, void>>> {
163 using Set = absl::flat_hash_set<T, CompareOrHashT>;
164 using Map = absl::flat_hash_map<T, int, CompareOrHashT>;
165 };
166
167 // Specialization for when U is a hash functor and Eq is provided (not void).
168 template <typename U, typename V>
170 U, V,
171 absl::enable_if_t<std::is_integral<decltype(std::declval<const U&>()(
172 std::declval<const T&>()))>::value &&
173 !std::is_same_v<V, void>>> {
174 using Set = absl::flat_hash_set<T, CompareOrHashT, Eq>;
175 using Map = absl::flat_hash_map<T, int, CompareOrHashT, Eq>;
176 };
177
180};
181
182} // namespace internal
183
184// Usage:
185// ConnectedComponentsFinder<MyNodeType> cc;
186// cc.AddNode(node1);
187// cc.AddNode(node2);
188// cc.AddEdge(node1, node2);
189// ... repeating, adding nodes and edges as needed. Adding an edge
190// will automatically also add the two nodes at its ends, if they
191// haven't already been added.
192// vector<set<MyNodeType> > components;
193// cc.FindConnectedComponents(&components);
194// Each entry in components now contains all the nodes in a single
195// connected component.
196//
197// Protocol buffers can be used as the node type. Equality and hash functions
198// for protocol buffers can be found in ortools/base/message_hasher.h.
199//
200// Usage with flat_hash_set:
201// using ConnectedComponentType = flat_hash_set<MyNodeType>;
202// ConnectedComponentsFinder<ConnectedComponentType::key_type,
203// ConnectedComponentType::hasher,
204// ConnectedComponentType::key_equal>
205// cc;
206// ...
207// vector<ConnectedComponentType> components;
208// cc.FindConnectedComponents(&components);
209//
210// If you want to, you can continue adding nodes and edges after calling
211// FindConnectedComponents, then call it again later.
212//
213// If your node type isn't STL-friendly, then you can use pointers to
214// it instead:
215// ConnectedComponentsFinder<MySTLUnfriendlyNodeType*> cc;
216// cc.AddNode(&node1);
217// ... and so on...
218// Of course, in this usage, the connected components finder retains
219// these pointers through its lifetime (though it doesn't dereference them).
220template <typename T, typename CompareOrHashT = std::less<T>,
221 typename Eq = void>
223 public:
224 using Set =
225 typename internal::ConnectedComponentsTypeHelper<T, CompareOrHashT,
226 Eq>::Set;
227
228 // Constructs a connected components finder.
230
233 delete;
234
235 // Adds a node in the graph. It is OK to add the same node more than
236 // once; additions after the first have no effect.
237 void AddNode(T node) { LookupOrInsertNode<true>(node); }
238
239 // Adds an edge in the graph. Also adds both endpoint nodes as necessary.
240 // It is not an error to add the same edge twice. Self-edges are OK too.
241 // Returns true if the two nodes are newly connected, and false if they were
242 // already connected.
243 bool AddEdge(T node1, T node2) {
244 return delegate_.AddEdge(LookupOrInsertNode<false>(node1),
245 LookupOrInsertNode<false>(node2));
246 }
247
248 // Returns true iff both nodes are in the same connected component.
249 // Returns false if either node has not been already added with AddNode.
250 bool Connected(T node1, T node2) {
251 return delegate_.Connected(gtl::FindWithDefault(index_, node1, -1),
252 gtl::FindWithDefault(index_, node2, -1));
253 }
254
255 // Finds the connected component containing a node, and returns the
256 // total number of nodes in that component. Returns zero iff the
257 // node has not been already added with AddNode.
258 int GetSize(T node) {
259 return delegate_.GetSize(gtl::FindWithDefault(index_, node, -1));
260 }
261
262 // Finds all the connected components and assigns them to components.
263 // Components are ordered in the same way nodes were added, i.e. if node 'b'
264 // was added before node 'c', then either:
265 // - 'c' belongs to the same component as a node 'a' added before 'b', or
266 // - the component for 'c' comes after the one for 'b'.
267 // There are two versions:
268 // - The first one returns the result, and stores each component in a vector.
269 // This is the preferred version.
270 // - The second one populates the result, and stores each component in a set.
271 std::vector<std::vector<T>> FindConnectedComponents() {
272 const auto component_ids = delegate_.GetComponentIds();
273 std::vector<std::vector<T>> components(delegate_.GetNumberOfComponents());
274 for (const auto& elem_id : index_) {
275 components[component_ids[elem_id.second]].push_back(elem_id.first);
276 }
277 return components;
278 }
279 void FindConnectedComponents(std::vector<Set>* components) {
280 const auto component_ids = delegate_.GetComponentIds();
281 components->clear();
282 components->resize(delegate_.GetNumberOfComponents());
283 for (const auto& elem_id : index_) {
284 components->at(component_ids[elem_id.second]).insert(elem_id.first);
285 }
286 }
287
288 // Returns the current number of connected components.
289 // This number can change as the new nodes or edges are added.
291 return delegate_.GetNumberOfComponents();
292 }
293
294 // Returns the current number of added distinct nodes.
295 // This includes nodes added explicitly via the calls to AddNode() method
296 // and implicitly via the calls to AddEdge() method.
297 // Nodes that were added several times only count once.
298 int GetNumberOfNodes() const { return delegate_.GetNumberOfNodes(); }
299
300 private:
301 // Returns the index for the given node. If the node does not exist and
302 // update_delegate is true, explicitly add the node to the delegate.
303 template <bool update_delegate>
304 int LookupOrInsertNode(T node) {
305 const auto result = index_.emplace(node, index_.size());
306 const int node_id = result.first->second;
307 if (update_delegate && result.second) {
308 // A new index was created.
309 delegate_.SetNumberOfNodes(node_id + 1);
310 }
311 return node_id;
312 }
313
316 index_;
317};
318
319// =============================================================================
320// Implementations of the method templates
321// =============================================================================
322namespace util {
323template <class UndirectedGraph>
324std::vector<int> GetConnectedComponents(int num_nodes,
325 const UndirectedGraph& graph) {
326 std::vector<int> component_of_node(num_nodes, -1);
327 std::vector<int> bfs_queue;
328 int num_components = 0;
329 for (int src = 0; src < num_nodes; ++src) {
330 if (component_of_node[src] >= 0) continue;
331 bfs_queue.push_back(src);
332 component_of_node[src] = num_components;
333 for (int num_visited = 0; num_visited < bfs_queue.size(); ++num_visited) {
334 const int node = bfs_queue[num_visited];
335 for (const int neighbor : graph[node]) {
336 if (component_of_node[neighbor] >= 0) continue;
337 component_of_node[neighbor] = num_components;
338 bfs_queue.push_back(neighbor);
339 }
340 }
341 ++num_components;
342 bfs_queue.clear();
343 }
344 return component_of_node;
345}
346} // namespace util
347
348#endif // UTIL_GRAPH_CONNECTED_COMPONENTS_H_
std::vector< std::vector< T > > FindConnectedComponents()
bool AddEdge(T node1, T node2)
ConnectedComponentsFinder(const ConnectedComponentsFinder &)=delete
ConnectedComponentsFinder & operator=(const ConnectedComponentsFinder &)=delete
bool Connected(T node1, T node2)
typename internal::ConnectedComponentsTypeHelper< T, CompareOrHashT, Eq >::Set Set
void FindConnectedComponents(std::vector< Set > *components)
bool AddEdge(int node1, int node2)
DenseConnectedComponentsFinder(const DenseConnectedComponentsFinder &)=default
DenseConnectedComponentsFinder & operator=(DenseConnectedComponentsFinder &&)=default
DenseConnectedComponentsFinder(DenseConnectedComponentsFinder &&)=default
bool Connected(int node1, int node2)
DenseConnectedComponentsFinder & operator=(const DenseConnectedComponentsFinder &)=default
const std::vector< int > & GetComponentRoots()
Definition: cleanup.h:22
const Collection::value_type::second_type & FindWithDefault(const Collection &collection, const typename Collection::value_type::first_type &key, const typename Collection::value_type::second_type &value)
Definition: map_util.h:29
std::vector< int > GetConnectedComponents(int num_nodes, const UndirectedGraph &graph)
typename SelectContainer< CompareOrHashT, Eq >::Map Map
typename SelectContainer< CompareOrHashT, Eq >::Set Set