Skip to content
Snippets Groups Projects
Commit d36c7525 authored by Bruno Freitas Tissei's avatar Bruno Freitas Tissei
Browse files

Add tarjan algorithm

parent 4f29608f
No related branches found
No related tags found
No related merge requests found
/**
* Tarjan - Strongly Connected Components
*
* Complexity (Time): O(n + m)
* Complexity (Space): O(n + m)
*/
vector<int> graph[MAX];
vector<int> scc[MAX];
stack<int> S;
int ncomp, ind;
int cont[MAX], parent[MAX];
int low[MAX], L[MAX];
// Fills scc with strongly connected components of graph
void dfs(int x) {
L[x] = ind;
low[x] = ind++;
cont[x] = 1;
S.push(x);
for (auto i : graph[x])
if (L[i] == -1) {
dfs(i);
low[x] = min(low[x], low[i]);
} else if (cont[i])
low[x] = min(low[x], L[i]);
if (low[x] == L[x]) {
int w;
ncomp++;
do {
w = S.top(); S.pop();
cont[w] = 0;
scc[ncomp].pb(w);
} while (w != x);
}
}
// Return number of SCCs
int tarjan(int n) {
memset(L, -1, sizeof L);
ncomp = ind = 0;
for (int i = 0; i < n; ++i)
if (L[i] == -1)
dfs(i);
return ncomp;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment