GraphLib
Bearbeitung der Aufgabe Mini Graph Library für OOP WiSe 2023/24
Loading...
Searching...
No Matches
tarjan.h
Go to the documentation of this file.
1#ifndef GRAPHLIB_ALGORITHMS_TARJAN_H
2#define GRAPHLIB_ALGORITHMS_TARJAN_H
3
4#include <functional>
5#include <map>
6#include <stack>
7
9
17
18namespace GraphLib {
19
24
35template <Internal::valid_directed_graph_type G>
36std::vector<std::vector<typename G::id_type>> tarjan(const G& graph)
37{
38 using id_type = typename G::id_type;
39
40 std::vector<std::vector<id_type>> sccs;
41 std::map<id_type, int> disc; // discovery values; Order, in der die Nodes besucht wurden
42 std::map<id_type, int> low; // niedrigste erreichbare discovery value aka lowlink value
43 std::map<id_type, bool> on_stack;
44 std::stack<id_type> st;
45 int time = 0;
46
47 std::function<void(id_type)> strongconnect = [&](id_type node) {
48 disc[node] = low[node] = ++time;
49 st.push(node);
50 on_stack[node] = true;
51
52 // starte DFS für Nachfolger
53 for (id_type neighbor : graph.get_neighbors(node)) {
54 if (disc.find(neighbor) == disc.end()) {
55 // Nachbar noch nicht besucht
56 strongconnect(neighbor);
57 low[node] = std::min(low[node], low[neighbor]);
58 } else if (on_stack[neighbor]) {
59 // Update low link value nur wenn nachbar auf stack
60 low[node] = std::min(low[node], disc[neighbor]);
61 }
62 }
63
64 // Falls node root von SCC, poppe Stack und erschaffe component;
65 // geschieht, falls die discovery order gleich des lowlink value ist,
66 // also falls die Node sich selber erreichen kann, nachdem DFS durch ist.
67 if (low[node] == disc[node]) {
68 std::vector<id_type> component;
69 id_type w;
70 do {
71 w = st.top();
72 st.pop();
73 on_stack[w] = false;
74 component.push_back(w);
75 } while (w != node);
76 sccs.push_back(component);
77 }
78 };
79
80 // Finde SCCs für jede Node; Nodes, die schon teil einer SCC sind und eine disc-value haben, werden ignoriert
81 for (const auto& node : graph.get_nodes()) {
82 if (disc.find(node) == disc.end()) {
83 strongconnect(node);
84 }
85 }
86
87 return sccs;
88}
89
90} // namespace GraphLib
91
92#endif
Defines C++20 concepts used for type constraints in the GraphLib library.
std::vector< std::vector< typename G::id_type > > tarjan(const G &graph)
Finds all strongly connected components (SCCs) in a directed graph using Tarjan's algorithm.
Definition tarjan.h:36