Files
reachability-algorithms/algorithm/tarjan.h
2022-09-12 00:08:45 +03:00

88 lines
1.8 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::map<T, std::set<T>> adjMatrix) : adjMatrix(adjMatrix) {}
auto execute();
void strongConnect(const T& u);
void setGraph(std::map<T, std::set<T>> adjMatrix);
private:
std::map<T, std::set<T>> adjMatrix;
std::stack<T> S;
std::int16_t index = 0;
std::vector<SCC<T>> SCCs;
struct Vertex {
int index = -1;
int lowlink = -1;
bool onStack = false;
};
std::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 : adjMatrix[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::map<T, std::set<T>> scc;
bool finished = false;
do {
const auto w = S.top();
S.pop();
vmap[w].onStack = false;
scc[w] = adjMatrix[w];
finished = (w == u);
} while (!finished);
SCCs.push_back({ scc, static_cast<T>(vmap[u].lowlink + 1) });
}
}
template<typename T>
auto Tarjan<T>::execute() {
for (const auto& u : std::views::keys(adjMatrix)) {
if (vmap[u].index == -1)
strongConnect(u);
}
return SCCs;
}
template<typename T>
void Tarjan<T>::setGraph(std::map<T, std::set<T>> adjMatrix) {
this->adjMatrix = adjMatrix;
}
} // namespace algo
#endif