Files
reachability-algorithms/include/algorithm/tarjan.h

85 lines
1.7 KiB
C++

#ifndef TARJAN_H_
#define TARJAN_H_
#include "graph/scc.h"
#include <stack>
#include <vector>
#include <ranges>
using namespace graph;
namespace algo {
template<typename T>
class Tarjan {
public:
Tarjan() = default;
Tarjan(std::unordered_map<T, std::unordered_set<T>> adjList) : adjList(adjList) {}
//
auto execute();
//
void strongConnect(const T& u);
private:
std::unordered_map<T, std::unordered_set<T>> adjList;
std::stack<T> S;
std::int16_t index = 0;
std::vector<SCC<T>> SCCs;
T cid;
struct Vertex {
int index = -1;
int lowlink = -1;
bool onStack = false;
};
std::unordered_map<T, Vertex> vmap;
};
template<typename T>
void Tarjan<T>::strongConnect(const T& u) {
vmap[u].index = vmap[u].lowlink = index++;
S.push(u);
vmap[u].onStack = true;
for (const auto& w : adjList[u]) {
if (vmap[w].index == -1) {
strongConnect(w);
vmap[u].lowlink = std::min(vmap[u].lowlink, vmap[w].lowlink);
} else if (vmap[w].onStack) {
vmap[u].lowlink = std::min(vmap[u].lowlink, vmap[w].index);
}
}
// If u is a root node, pop the stack and generate an SCC
if (vmap[u].lowlink == vmap[u].index) {
std::unordered_map<T, std::unordered_set<T>> scc;
bool finished = false;
cid = S.top();
do {
const auto w = S.top();
S.pop();
vmap[w].onStack = false;
scc[w] = adjList[w];
finished = (w == u);
} while (!finished);
SCCs.push_back({ scc, static_cast<T>(cid) });
}
}
template<typename T>
auto Tarjan<T>::execute() {
for (const auto& u : std::views::keys(adjList)) {
if (vmap[u].index == -1)
strongConnect(u);
}
return SCCs;
}
} // namespace algo
#endif