C++ Reference

C++ Reference: Graph

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"
52#include "ortools/base/logging.h"
53#include "ortools/base/map_util.h"
54#include "ortools/base/ptr_util.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>
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 E = void>
147 using Set = std::set<T, CompareOrHashT>;
148 using Map = std::map<T, int, CompareOrHashT>;
149 };
150
151 // The expression inside decltype is basically saying that "H(x)" is
152 // well-formed, where H is an instance of U and x is an instance of T, and is
153 // a value of integral type. That is, we are "duck-typing" on whether U looks
154 // like a hash functor.
155 template <typename U>
157 U, absl::enable_if_t<std::is_integral<decltype(std::declval<const U&>()(
158 std::declval<const T&>()))>::value>> {
159 using Set = absl::flat_hash_set<T, CompareOrHashT>;
160 using Map = absl::flat_hash_map<T, int, CompareOrHashT>;
161 };
162
165};
166
167} // namespace internal
168
169// Usage:
170// ConnectedComponentsFinder<MyNodeType> cc;
171// cc.AddNode(node1);
172// cc.AddNode(node2);
173// cc.AddEdge(node1, node2);
174// ... repeating, adding nodes and edges as needed. Adding an edge
175// will automatically also add the two nodes at its ends, if they
176// haven't already been added.
177// vector<set<MyNodeType> > components;
178// cc.FindConnectedComponents(&components);
179// Each entry in components now contains all the nodes in a single
180// connected component.
181//
182// Usage with flat_hash_set:
183// using ConnectedComponentType = flat_hash_set<MyNodeType>;
184// ConnectedComponentsFinder<ConnectedComponentType::key_type,
185// ConnectedComponentType::hasher>
186// cc;
187// ...
188// vector<ConnectedComponentType> components;
189// cc.FindConnectedComponents(&components);
190//
191// If you want to, you can continue adding nodes and edges after calling
192// FindConnectedComponents, then call it again later.
193//
194// If your node type isn't STL-friendly, then you can use pointers to
195// it instead:
196// ConnectedComponentsFinder<MySTLUnfriendlyNodeType*> cc;
197// cc.AddNode(&node1);
198// ... and so on...
199// Of course, in this usage, the connected components finder retains
200// these pointers through its lifetime (though it doesn't dereference them).
201template <typename T, typename CompareOrHashT = std::less<T>>
203 public:
204 // Constructs a connected components finder.
206
209 delete;
210
211 // Adds a node in the graph. It is OK to add the same node more than
212 // once; additions after the first have no effect.
213 void AddNode(T node) { LookupOrInsertNode<true>(node); }
214
215 // Adds an edge in the graph. Also adds both endpoint nodes as necessary.
216 // It is not an error to add the same edge twice. Self-edges are OK too.
217 // Returns true if the two nodes are newly connected, and false if they were
218 // already connected.
219 bool AddEdge(T node1, T node2) {
220 return delegate_.AddEdge(LookupOrInsertNode<false>(node1),
221 LookupOrInsertNode<false>(node2));
222 }
223
224 // Returns true iff both nodes are in the same connected component.
225 // Returns false if either node has not been already added with AddNode.
226 bool Connected(T node1, T node2) {
227 return delegate_.Connected(gtl::FindWithDefault(index_, node1, -1),
228 gtl::FindWithDefault(index_, node2, -1));
229 }
230
231 // Finds the connected component containing a node, and returns the
232 // total number of nodes in that component. Returns zero iff the
233 // node has not been already added with AddNode.
234 int GetSize(T node) {
235 return delegate_.GetSize(gtl::FindWithDefault(index_, node, -1));
236 }
237
238 // Finds all the connected components and assigns them to components.
239 // Components are ordered in the same way nodes were added, i.e. if node 'b'
240 // was added before node 'c', then either:
241 // - 'c' belongs to the same component as a node 'a' added before 'b', or
242 // - the component for 'c' comes after the one for 'b'.
243 // There are two versions:
244 // - The first one returns the result, and stores each component in a vector.
245 // This is the preferred version.
246 // - The second one populates the result, and stores each component in a set.
247 std::vector<std::vector<T>> FindConnectedComponents() {
248 const auto component_ids = delegate_.GetComponentIds();
249 std::vector<std::vector<T>> components(delegate_.GetNumberOfComponents());
250 for (const auto& elem_id : index_) {
251 components[component_ids[elem_id.second]].push_back(elem_id.first);
252 }
253 return components;
254 }
256 std::vector<typename internal::ConnectedComponentsTypeHelper<
257 T, CompareOrHashT>::Set>* components) {
258 const auto component_ids = delegate_.GetComponentIds();
259 components->clear();
260 components->resize(delegate_.GetNumberOfComponents());
261 for (const auto& elem_id : index_) {
262 components->at(component_ids[elem_id.second]).insert(elem_id.first);
263 }
264 }
265
266 // Returns the current number of connected components.
267 // This number can change as the new nodes or edges are added.
269 return delegate_.GetNumberOfComponents();
270 }
271
272 // Returns the current number of added distinct nodes.
273 // This includes nodes added explicitly via the calls to AddNode() method
274 // and implicitly via the calls to AddEdge() method.
275 // Nodes that were added several times only count once.
276 int GetNumberOfNodes() const { return delegate_.GetNumberOfNodes(); }
277
278 private:
279 // Returns the index for the given node. If the node does not exist and
280 // update_delegate is true, explicitly add the node to the delegate.
281 template <bool update_delegate>
282 int LookupOrInsertNode(T node) {
283 const auto result = index_.emplace(node, index_.size());
284 const int node_id = result.first->second;
285 if (update_delegate && result.second) {
286 // A new index was created.
287 delegate_.SetNumberOfNodes(node_id + 1);
288 }
289 return node_id;
290 }
291
294 index_;
295};
296
297// =============================================================================
298// Implementations of the method templates
299// =============================================================================
300namespace util {
301template <class UndirectedGraph>
302std::vector<int> GetConnectedComponents(int num_nodes,
303 const UndirectedGraph& graph) {
304 std::vector<int> component_of_node(num_nodes, -1);
305 std::vector<int> bfs_queue;
306 int num_components = 0;
307 for (int src = 0; src < num_nodes; ++src) {
308 if (component_of_node[src] >= 0) continue;
309 bfs_queue.push_back(src);
310 component_of_node[src] = num_components;
311 for (int num_visited = 0; num_visited < bfs_queue.size(); ++num_visited) {
312 const int node = bfs_queue[num_visited];
313 for (const int neighbor : graph[node]) {
314 if (component_of_node[neighbor] >= 0) continue;
315 component_of_node[neighbor] = num_components;
316 bfs_queue.push_back(neighbor);
317 }
318 }
319 ++num_components;
320 bfs_queue.clear();
321 }
322 return component_of_node;
323}
324} // namespace util
325
326#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
void FindConnectedComponents(std::vector< typename internal::ConnectedComponentsTypeHelper< T, CompareOrHashT >::Set > *components)
bool Connected(T node1, T node2)
bool AddEdge(int node1, int node2)
DenseConnectedComponentsFinder(const DenseConnectedComponentsFinder &)=default
DenseConnectedComponentsFinder & operator=(DenseConnectedComponentsFinder &&)=default
std::vector< int > GetComponentIds()
DenseConnectedComponentsFinder(DenseConnectedComponentsFinder &&)=default
bool Connected(int node1, int node2)
DenseConnectedComponentsFinder & operator=(const DenseConnectedComponentsFinder &)=default
void SetNumberOfNodes(int num_nodes)
const std::vector< int > & GetComponentRoots()
std::vector< int > GetConnectedComponents(int num_nodes, const UndirectedGraph &graph)
typename SelectContainer< CompareOrHashT >::Set Set
typename SelectContainer< CompareOrHashT >::Map Map