Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
strongly_connected_components.h
Go to the documentation of this file.
1// Copyright 2010-2024 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 "absl/log/check.h"
50#include "absl/types/span.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>
73void FindStronglyConnectedComponents(NodeIndex num_nodes, const Graph& graph,
74 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; }
92};
93
94// This implementation is slightly different than a classical iterative version
95// of Tarjan's strongly connected components algorithm. But basically it is
96// still an iterative DFS. We use a class so memory can be reused if one needs
97// to compute many SCC in a row. It also allows more complex behavior in the
98// Graph or SccOutput class that might inspect the current state of the
99// algorithm.
100//
101// TODO(user): Possible optimizations:
102// - Try to reserve the vectors which sizes are bounded by num_nodes.
103// - Use an index rather than doing push_back(), pop_back() on them.
104template <typename NodeIndex, typename Graph, typename SccOutput>
106 public:
107 void FindStronglyConnectedComponents(const NodeIndex num_nodes,
108 const Graph& graph,
109 SccOutput* components) {
110 // Reset the class fields.
111 scc_stack_.clear();
112 scc_start_index_.clear();
113 node_index_.assign(num_nodes, 0);
114 node_to_process_.clear();
115
116 // Caching the pointer to this vector.data() avoid re-fetching it and help.
117 absl::Span<NodeIndex> node_index = absl::MakeSpan(node_index_);
118
119 // Optimization. This will always be equal to scc_start_index_.back() except
120 // when scc_stack_ is empty, in which case its value does not matter.
121 NodeIndex current_scc_start = 0;
122
123 // Loop over all the nodes not yet settled and start a DFS from each of
124 // them.
125 for (NodeIndex base_node = 0; base_node < num_nodes; ++base_node) {
126 if (node_index[base_node] != 0) continue;
127 DCHECK_EQ(0, node_to_process_.size());
128 node_to_process_.push_back(base_node);
129 do {
130 const NodeIndex node = node_to_process_.back();
131 const NodeIndex index = node_index[node];
132 if (index == 0) {
133 // We continue the dfs from this node and set its 1-based index.
134 scc_stack_.push_back(node);
135 current_scc_start = scc_stack_.size();
136 node_index[node] = current_scc_start;
137 scc_start_index_.push_back(current_scc_start);
138
139 // Enqueue all its adjacent nodes.
140 NodeIndex min_head_index = kSettledIndex;
141 for (const NodeIndex head : graph[node]) {
142 const NodeIndex head_index = node_index[head];
143 if (head_index == 0) {
144 node_to_process_.push_back(head);
145 } else {
146 // Note that if head_index == kSettledIndex, nothing happens.
147 min_head_index = std::min(min_head_index, head_index);
148 }
149 }
150
151 // Update the start of this strongly connected component.
152 // Note that scc_start_index_ can never be empty since it first
153 // element is 1 and by definition min_head_index is 1-based and can't
154 // be 0.
155 while (current_scc_start > min_head_index) {
156 scc_start_index_.pop_back();
157 current_scc_start = scc_start_index_.back();
158 }
159 } else {
160 node_to_process_.pop_back();
161 if (current_scc_start == index) {
162 // We found a strongly connected component.
163 components->emplace_back(&scc_stack_[current_scc_start - 1],
164 &scc_stack_[0] + scc_stack_.size());
165 for (int i = current_scc_start - 1; i < scc_stack_.size(); ++i) {
166 node_index[scc_stack_[i]] = kSettledIndex;
167 }
168 scc_stack_.resize(current_scc_start - 1);
169 scc_start_index_.pop_back();
170 current_scc_start =
171 scc_start_index_.empty() ? 0 : scc_start_index_.back();
172 }
173 }
174 } while (!node_to_process_.empty());
175 }
176 }
177
178 // Advanced usage. This can be used in either the Graph or SccOutput template
179 // class to query the current state of the algorithm. It allows to build more
180 // complex variant based on the core DFS algo.
181 bool NodeIsInCurrentDfsPath(NodeIndex node) const {
182 return node_index_[node] > 0 && node_index_[node] < kSettledIndex;
183 }
184
185 private:
186 static constexpr NodeIndex kSettledIndex =
187 std::numeric_limits<NodeIndex>::max();
188
189 // Each node expanded by the DFS will be pushed on this stack. A node is only
190 // popped back when its strongly connected component has been explored and
191 // outputted.
192 std::vector<NodeIndex> scc_stack_;
193
194 // This is equivalent to the "low link" of a node in Tarjan's algorithm.
195 // Basically, scc_start_index_.back() represent the 1-based index in
196 // scc_stack_ of the beginning of the current strongly connected component.
197 // All the nodes after this index will be on the same component.
198 std::vector<NodeIndex> scc_start_index_;
199
200 // Each node is assigned an index which changes 2 times in the algorithm:
201 // - Everyone starts with an index of 0 which means unexplored.
202 // - The first time they are explored by the DFS and pushed on scc_stack_,
203 // they get their 1-based index on this stack.
204 // - Once they have been processed and outputted to components, they are said
205 // to be settled, and their index become kSettledIndex.
206 std::vector<NodeIndex> node_index_;
207
208 // This is a well known way to do an efficient iterative DFS. Each time a node
209 // is explored, all its adjacent nodes are pushed on this stack. The iterative
210 // dfs processes the nodes one by one by popping them back from here.
211 std::vector<NodeIndex> node_to_process_;
212};
213
214// Simple wrapper function for most usage.
215template <typename NodeIndex, typename Graph, typename SccOutput>
216void FindStronglyConnectedComponents(const NodeIndex num_nodes,
217 const Graph& graph,
218 SccOutput* components) {
220 return helper.FindStronglyConnectedComponents(num_nodes, graph, components);
221}
222
223#endif // UTIL_GRAPH_STRONGLY_CONNECTED_COMPONENTS_H_
void FindStronglyConnectedComponents(const NodeIndex num_nodes, const Graph &graph, SccOutput *components)
int64_t b
Definition table.cc:45
GraphType graph
int head_index
int index
int head
void FindStronglyConnectedComponents(NodeIndex num_nodes, const Graph &graph, SccOutput *components)
Simple wrapper function for most usage.
void emplace_back(NodeIndex const *b, NodeIndex const *e)