C++ Reference

C++ Reference: Graph

strongly_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// This code computes the strongly connected components of a directed graph,
15// and presents them sorted by reverse topological order.
16//
17// It implements an efficient version of Tarjan's strongly connected components
18// algorithm published in: Tarjan, R. E. (1972), "Depth-first search and linear
19// graph algorithms", SIAM Journal on Computing.
20//
21// A description can also be found here:
22// http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
23//
24// SIMPLE EXAMPLE:
25//
26// Fill a vector<vector<int>> graph; representing your graph adjacency lists.
27// That is, graph[i] contains the nodes adjacent to node #i. The nodes must be
28// integers in [0, num_nodes). Then just do:
29//
30// vector<vector<int>> components;
31// FindStronglyConnectedComponents(
32// static_cast<int>(graph.size()), graph, &components);
33//
34// The nodes of each strongly connected components will be listed in each
35// subvector of components. The components appear in reverse topological order:
36// outgoing arcs from a component will only be towards earlier components.
37//
38// IMPORTANT: num_nodes will be the number of nodes of the graph. Its type
39// is the type used internally by the algorithm. It is why it is better to
40// convert it to int or even int32_t rather than using size_t which takes 64
41// bits.
42
43#ifndef UTIL_GRAPH_STRONGLY_CONNECTED_COMPONENTS_H_
44#define UTIL_GRAPH_STRONGLY_CONNECTED_COMPONENTS_H_
45
46#include <limits>
47#include <vector>
48
49#include "ortools/base/logging.h"
50#include "ortools/base/macros.h"
51
52// Finds the strongly connected components of a directed graph. It is templated
53// so it can be used in many contexts. See the simple example above for the
54// easiest use case.
55//
56// The requirement of the different types are:
57// - The type NodeIndex must be an integer type representing a node of the
58// graph. The nodes must be in [0, num_nodes). It can be unsigned.
59// - The type Graph must provide a [] operator such that the following code
60// iterates over the adjacency list of the given node:
61// for (const NodeIndex head : graph[node]) {}
62// - The type SccOutput must implement the function:
63// emplace_back(NodeIndex const* begin, NodeIndex const* end);
64// It will be called with the connected components of the given graph as they
65// are found (In the reverse topological order).
66//
67// More practical details on the algorithm:
68// - It deals properly with self-loop and duplicate nodes.
69// - It is really fast! and work in O(nodes + edges).
70// - Its memory usage is also bounded by O(nodes + edges) but in practice it
71// uses less than the input graph.
72template <typename NodeIndex, typename Graph, typename SccOutput>
74 const Graph& graph, SccOutput* components);
75
76// A simple custom output class that just counts the number of SCC. Not
77// allocating many vectors can save both space and speed if your graph is large.
78//
79// Note: If this matters, you probably don't want to use vector<vector<int>> as
80// an input either. See StaticGraph in ortools/graph/graph.h
81// for an efficient graph data structure compatible with this algorithm.
82template <typename NodeIndex>
85 void emplace_back(NodeIndex const* b, NodeIndex const* e) {
87 }
88 // This is just here so this class can transparently replace a code that
89 // use vector<vector<int>> as an SccOutput, and get its size with size().
90 int size() const { return number_of_components; }
91};
92
93// This implementation is slightly different than a classical iterative version
94// of Tarjan's strongly connected components algorithm. But basically it is
95// still an iterative DFS. We use a class so memory can be reused if one needs
96// to compute many SCC in a row. It also allows more complex behavior in the
97// Graph or SccOutput class that might inspect the current state of the
98// algorithm.
99//
100// TODO(user): Possible optimizations:
101// - Try to reserve the vectors which sizes are bounded by num_nodes.
102// - Use an index rather than doing push_back(), pop_back() on them.
103template <typename NodeIndex, typename Graph, typename SccOutput>
105 public:
107 const Graph& graph,
108 SccOutput* components) {
109 // Reset the class fields.
110 scc_stack_.clear();
111 scc_start_index_.clear();
112 node_index_.assign(num_nodes, 0);
113 node_to_process_.clear();
114
115 // Optimization. This will always be equal to scc_start_index_.back() except
116 // when scc_stack_ is empty, in which case its value does not matter.
117 NodeIndex current_scc_start = 0;
118
119 // Loop over all the nodes not yet settled and start a DFS from each of
120 // them.
121 for (NodeIndex base_node = 0; base_node < num_nodes; ++base_node) {
122 if (node_index_[base_node] != 0) continue;
123 DCHECK_EQ(0, node_to_process_.size());
124 node_to_process_.push_back(base_node);
125 do {
126 const NodeIndex node = node_to_process_.back();
127 const NodeIndex index = node_index_[node];
128 if (index == 0) {
129 // We continue the dfs from this node and set its 1-based index.
130 scc_stack_.push_back(node);
131 current_scc_start = scc_stack_.size();
132 node_index_[node] = current_scc_start;
133 scc_start_index_.push_back(current_scc_start);
134
135 // Enqueue all its adjacent nodes.
136 NodeIndex min_head_index = kSettledIndex;
137 for (const NodeIndex head : graph[node]) {
138 const NodeIndex head_index = node_index_[head];
139 if (head_index == 0) {
140 node_to_process_.push_back(head);
141 } else {
142 // Note that if head_index == kSettledIndex, nothing happens.
143 min_head_index = std::min(min_head_index, head_index);
144 }
145 }
146
147 // Update the start of this strongly connected component.
148 // Note that scc_start_index_ can never be empty since it first
149 // element is 1 and by definition min_head_index is 1-based and can't
150 // be 0.
151 while (current_scc_start > min_head_index) {
152 scc_start_index_.pop_back();
153 current_scc_start = scc_start_index_.back();
154 }
155 } else {
156 node_to_process_.pop_back();
157 if (current_scc_start == index) {
158 // We found a strongly connected component.
159 components->emplace_back(&scc_stack_[current_scc_start - 1],
160 &scc_stack_[0] + scc_stack_.size());
161 for (int i = current_scc_start - 1; i < scc_stack_.size(); ++i) {
162 node_index_[scc_stack_[i]] = kSettledIndex;
163 }
164 scc_stack_.resize(current_scc_start - 1);
165 scc_start_index_.pop_back();
166 current_scc_start =
167 scc_start_index_.empty() ? 0 : scc_start_index_.back();
168 }
169 }
170 } while (!node_to_process_.empty());
171 }
172 }
173
174 // Advanced usage. This can be used in either the Graph or SccOutput template
175 // class to query the current state of the algorithm. It allows to build more
176 // complex variant based on the core DFS algo.
178 return node_index_[node] > 0 && node_index_[node] < kSettledIndex;
179 }
180
181 private:
182 static constexpr NodeIndex kSettledIndex =
183 std::numeric_limits<NodeIndex>::max();
184
185 // Each node expanded by the DFS will be pushed on this stack. A node is only
186 // popped back when its strongly connected component has been explored and
187 // outputted.
188 std::vector<NodeIndex> scc_stack_;
189
190 // This is equivalent to the "low link" of a node in Tarjan's algorithm.
191 // Basically, scc_start_index_.back() represent the 1-based index in
192 // scc_stack_ of the beginning of the current strongly connected component.
193 // All the nodes after this index will be on the same component.
194 std::vector<NodeIndex> scc_start_index_;
195
196 // Each node is assigned an index which changes 2 times in the algorithm:
197 // - Everyone starts with an index of 0 which means unexplored.
198 // - The first time they are explored by the DFS and pushed on scc_stack_,
199 // they get their 1-based index on this stack.
200 // - Once they have been processed and outputted to components, they are said
201 // to be settled, and their index become kSettledIndex.
202 std::vector<NodeIndex> node_index_;
203
204 // This is a well known way to do an efficient iterative DFS. Each time a node
205 // is explored, all its adjacent nodes are pushed on this stack. The iterative
206 // dfs processes the nodes one by one by popping them back from here.
207 std::vector<NodeIndex> node_to_process_;
208};
209
210// Simple wrapper function for most usage.
211template <typename NodeIndex, typename Graph, typename SccOutput>
213 const Graph& graph,
214 SccOutput* components) {
216 return helper.FindStronglyConnectedComponents(num_nodes, graph, components);
217}
218
219#endif // UTIL_GRAPH_STRONGLY_CONNECTED_COMPONENTS_H_
void FindStronglyConnectedComponents(const NodeIndex num_nodes, const Graph &graph, SccOutput *components)
ListGraph Graph
Definition: graph.h:2362
void FindStronglyConnectedComponents(const NodeIndex num_nodes, const Graph &graph, SccOutput *components)
void emplace_back(NodeIndex const *b, NodeIndex const *e)