Skip to content

Instantly share code, notes, and snippets.

@v1k22
Last active May 26, 2019 10:31
Show Gist options
  • Select an option

  • Save v1k22/9b9b60efec7c27d256b66c35450f0072 to your computer and use it in GitHub Desktop.

Select an option

Save v1k22/9b9b60efec7c27d256b66c35450f0072 to your computer and use it in GitHub Desktop.
Tarjan's strongly connected component algorithm
/*
Below code is function which returns number of strongly connected components.
https://www.youtube.com/watch?v=TyWtx7q2D7Y
https://www.tutorialspoint.com/Tarjan-s-Algorithm-for-Strongly-Connected-Components
*/
int id;
int ans;
void dfs(int x,
vector < int > adj[],
vector < bool > &visited,
vector < int > &ids,
vector < int > &low,
stack < int > &s,
vector < bool > &in_stack) {
visited[x] = true;
in_stack[x] = true;
s.push(x);
ids[x] = low[x] = id++;
for (auto i : adj[x]) {
if (!visited[i]) {
dfs(i, adj, visited, ids, low, s, in_stack);
low[x] = min(low[x], low[i]);
} else if (in_stack[i]) {
low[x] = min(low[x], low[i]);
}
}
if (ids[x] == low[x]) {
while (s.top() != x) {
in_stack[s.top()] = false;
s.pop();
}
in_stack[s.top()] = false;
s.pop();
ans++;
}
}
int TarjanSCC(int V, vector<int> adj[]) {
ans = 0;
id = 0;
vector < int > ids(V, 0);
vector < int > low(V, 0);
vector < bool > visited(V, false);
vector < bool > in_stack(V, false);
stack < int > s;
for (int i = 0; i < V; i++) {
if (!visited[i])
dfs(i, adj, visited, ids, low, s, in_stack);
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment