LAB2 Jatin
LAB2 Jatin
Tarjan’s Algo
Jatin
2023BCD0014
Algorithm
1. Input Graph
• Accept the number of nodes n and edges m.
• Represent the graph as an adjacency list.
2. Initialize Variables
• disc: Stores discovery time for each node.
• low: Stores the smallest discovery time reachable from each node.
• st: A stack to keep track of nodes in the current DFS path.
• inStack: A boolean array to check whether a node is in the stack.
• ans: Stores all the SCCs.
• time: Global timer for assigning discovery times.
3. Perform Depth-First Search (DFS)
• For every unvisited node, start a DFS:
o Assign discovery time and low-link value to the node.
o Push the node onto the stack and mark it as part of the current DFS
path.
o Recursively visit all adjacent nodes:
▪ If an adjacent node has not been visited, recurse on it, and
update the current node's low-link value.
▪ If the adjacent node is already in the stack, update the current
node's low-link value to the discovery time of the adjacent
node.
4. Identify SCC Root
• After exploring all neighbours of a node:
o If the node's discovery time equals its low-link value, it is the root of
an SCC.
o Pop all nodes from the stack until the root is reached. These nodes
form an SCC.
o Add the SCC to the result.
5. Output the SCCs
• Print each SCC identified.
Problem Solving:
Code:
#include <bits/stdc++.h>
using namespace std;
void SCC(int node, vector<int> adj[], vector<int>& disc, vector<int>& low,
stack<int>& st, vector<bool>& inStack, vector<vector<int>>& ans, int&
time) {
disc[node] = low[node] = ++time;
st.push(node);
inStack[node] = true;
vector<int> adj[n];
cout << "Enter the directed edges (u -> v):\n";
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
}
vector<int> disc(n, -1), low(n, -1);
stack<int> st;
vector<bool> inStack(n, false);
vector<vector<int>> ans;
int time = 0;
for (int i = 0; i < n; i++) {
if (disc[i] == -1) {
SCC(i, adj, disc, low, st, inStack, ans, time);
}
}
cout << "Strongly Connected Components:\n";
for ( auto component : ans) {
for (int node : component) {
cout << node << " ";
}
cout << "\n";
}
return 0;
}