Problem of the day
You are given an unweighted directed graph having 'V' vertices and 'E' edges. Your task is to count the number of strongly connected components (SCCs) present in the graph.
A directed graph is said to be strongly connected if every vertex is reachable from every other vertex. The strongly connected components of a graph are the subgraphs which are themselves strongly connected.
Note :Use zero-based indexing for the vertices.
The given graph doesn’t contain any self-loops.
The very first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of every test case contains two space-separated integers ‘V’ and ‘E’ denoting the number of vertices and the number of edges present in the graph.
The next ‘E’ lines contain two space-separated integers ‘a’ and ‘b’ denoting a directed edge from vertex ‘a’ to ‘b’.
Output Format :
For each test case, return an integer denoting the number of strongly connected components (SCCs) present in the graph.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= V <= 10^4
0 <= E <= 10^4
0 <= a, b < V
Time Limit: 1 sec
1
5 6
0 1
1 2
1 4
2 3
3 2
4 0
2
For the first test case, the graph is shown below. There are two SCCs in the graph, which are enclosed in the boxes as shown in the image below.
2
1 0
4 4
0 1
1 2
2 3
3 1
1
2
Can you solve the problem using Kosaraju’s Algorithm?
Kosaraju’s algorithm can find the strongly connected components (SCCs) of a graph in linear time.
In the above approach, we have used DFS. You can also use BFS, but the idea will remain the same.
O(V + E), where ‘V’ and ‘E’ denote the number of vertices and edges in the graph, respectively.
We are traversing the complete graph twice where each traversal takes O(V + E) time. Finding the transpose of the graph takes O(V + E) time. Also, initialising the visited array takes O(V) time. Hence, the overall complexity is 2*O(V + E) + O(V + E) + O(V) = O(V + E).
O(V + E), where ‘V’ and ‘E’ denote the number of vertices and edges in the graph, respectively.
Extra space is required for the recursion stack. The maximum depth of the stack can be O(V). O(V) extra space is required for maintaining the stack and a visited array. Also, O(V+E) extra space is required for storing the adjacency list of the transpose graph. Hence, the overall space complexity is O(V) + O(V) + O(V) + O(V + E) = O(V + E).