C++ Reference

C++ Reference: Graph

strongly_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 // 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 std::vector<std::vector<int>> graph; representing your graph adjacency
27 // lists. That is, graph[i] contains the nodes adjacent to node #i. The nodes
28 // must be integers in [0, num_nodes). Then just do:
29 //
30 // std::vector<std::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 rather than using size_t which takes 64 bits.
41 
42 #ifndef UTIL_GRAPH_STRONGLY_CONNECTED_COMPONENTS_H_
43 #define UTIL_GRAPH_STRONGLY_CONNECTED_COMPONENTS_H_
44 
45 #include <limits>
46 #include <vector>
47 
48 #include "ortools/base/logging.h"
49 #include "ortools/base/macros.h"
50 
51 // Finds the strongly connected components of a directed graph. It is templated
52 // so it can be used in many contexts. See the simple example above for the
53 // easiest use case.
54 //
55 // The requirement of the different types are:
56 // - The type NodeIndex must be an integer type representing a node of the
57 // graph. The nodes must be in [0, num_nodes). It can be unsigned.
58 // - The type Graph must provide a [] operator such that the following code
59 // iterates over the adjacency list of the given node:
60 // for (const NodeIndex head : graph[node]) {}
61 // - The type SccOutput must implement the function:
62 // emplace_back(NodeIndex const* begin, NodeIndex const* end);
63 // It will be called with the connected components of the given graph as they
64 // are found (In the reverse topological order).
65 //
66 // More practical details on the algorithm:
67 // - It deals properly with self-loop and duplicate nodes.
68 // - It is really fast! and work in O(nodes + edges).
69 // - Its memory usage is also bounded by O(nodes + edges) but in practice it
70 // uses less than the input graph.
71 template <typename NodeIndex, typename Graph, typename SccOutput>
72 void FindStronglyConnectedComponents(const NodeIndex num_nodes,
73  const Graph& graph, SccOutput* components);
74 
75 // A simple custom output class that just counts the number of SCC. Not
76 // allocating many vectors can save both space and speed if your graph is large.
77 //
78 // Note: If this matters, you probably don't want to use
79 // std::vector<std::vector<int>> as an input either. See StaticGraph in
80 // ortools/graph/graph.h for an efficient graph data structure compatible with
81 // this algorithm.
82 template <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 std::vector<std::vector<int>> as an SccOutput, and get its size with
90  // size().
91  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.
97 //
98 // TODO(user): Possible optimizations:
99 // - Try to reserve the vectors which sizes are bounded by num_nodes.
100 // - Use an index rather than doing push_back(), pop_back() on them.
101 // - For a client needing many Scc computations one after another, it could be
102 // better to wrap this in a class so we don't need to allocate the stacks at
103 // each computation.
104 template <typename NodeIndex, typename Graph, typename SccOutput>
106  const Graph& graph,
107  SccOutput* components) {
108  // Each node expanded by the DFS will be pushed on this stack. A node is only
109  // popped back when its strongly connected component has been explored and
110  // outputted.
111  std::vector<NodeIndex> scc_stack;
112 
113  // This is equivalent to the "low link" of a node in Tarjan's algorithm.
114  // Basically, scc_start_index.back() represent the 1-based index in scc_stack
115  // of the beginning of the current strongly connected component. All the
116  // nodes after this index will be on the same component.
117  std::vector<NodeIndex> scc_start_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  // Each node is assigned an index which changes 2 times in the algorithm:
124  // - Everyone starts with an index of 0 which means unexplored.
125  // - The first time they are explored by the DFS and pushed on scc_stack, they
126  // get their 1-based index on this stack.
127  // - Once they have been processed and outputted to components, they are said
128  // to be settled, and their index become kSettledIndex.
129  std::vector<NodeIndex> node_index(num_nodes, 0);
130  constexpr NodeIndex kSettledIndex = std::numeric_limits<NodeIndex>::max();
131 
132  // This is a well known way to do an efficient iterative DFS. Each time a node
133  // is explored, all its adjacent nodes are pushed on this stack. The iterative
134  // dfs processes the nodes one by one by popping them back from here.
135  std::vector<NodeIndex> node_to_process;
136 
137  // Loop over all the nodes not yet settled and start a DFS from each of them.
138  for (NodeIndex base_node = 0; base_node < num_nodes; ++base_node) {
139  if (node_index[base_node] != 0) continue;
140  DCHECK_EQ(0, node_to_process.size());
141  node_to_process.push_back(base_node);
142  do {
143  const NodeIndex node = node_to_process.back();
144  const NodeIndex index = node_index[node];
145  if (index == 0) {
146  // We continue the dfs from this node and set its 1-based index.
147  scc_stack.push_back(node);
148  current_scc_start = scc_stack.size();
149  node_index[node] = current_scc_start;
150  scc_start_index.push_back(current_scc_start);
151 
152  // Enqueue all its adjacent nodes.
153  NodeIndex min_head_index = kSettledIndex;
154  for (const NodeIndex head : graph[node]) {
155  const NodeIndex head_index = node_index[head];
156  if (head_index == 0) {
157  node_to_process.push_back(head);
158  } else {
159  // Note that if head_index == kSettledIndex, nothing happens.
160  min_head_index = std::min(min_head_index, head_index);
161  }
162  }
163 
164  // Update the start of this strongly connected component.
165  // Note that scc_start_index can never be empty since it first element
166  // is 1 and by definition min_head_index is 1-based and can't be 0.
167  while (current_scc_start > min_head_index) {
168  scc_start_index.pop_back();
169  current_scc_start = scc_start_index.back();
170  }
171  } else {
172  node_to_process.pop_back();
173  if (current_scc_start == index) {
174  // We found a strongly connected component.
175  components->emplace_back(&scc_stack[current_scc_start - 1],
176  &scc_stack[0] + scc_stack.size());
177  for (int i = current_scc_start - 1; i < scc_stack.size(); ++i) {
178  node_index[scc_stack[i]] = kSettledIndex;
179  }
180  scc_stack.resize(current_scc_start - 1);
181  scc_start_index.pop_back();
182  current_scc_start =
183  scc_start_index.empty() ? 0 : scc_start_index.back();
184  }
185  }
186  } while (!node_to_process.empty());
187  }
188 }
189 
190 #endif // UTIL_GRAPH_STRONGLY_CONNECTED_COMPONENTS_H_
void emplace_back(NodeIndex const *b, NodeIndex const *e)
ListGraph Graph
Definition: graph.h:2356
void FindStronglyConnectedComponents(const NodeIndex num_nodes, const Graph &graph, SccOutput *components)