Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, Find the number of strongly connected components in the graph.
- You don't need to read input or print anything. Your task is to complete the function kosaraju() which takes the number of vertices V and adjacency list of the graph as inputs and returns an integer denoting the number of strongly connected components in the given graph.
- Expected Time Complexity: O(V+E).
- Expected Auxiliary Space: O(V).
- Procedure:
- 1.Find out the dfs traversal and store the processed(black) vertices in a stack .
- 2.Transpose matrix
- 3.pop each node from q and do dfs(called as ndfs in code) traversal of trans list if node is not visited
- 4. Count no of times the ndfs traversal took place which is nothing but no of SCC.Roots of these SSC are the ones that ndfs traversal through which has taken place
- """
- #User function Template for python3
- from collections import deque
- class Solution:
- #Function to find number of strongly connected components in the graph.
- def kosaraju(self, v, adj):
- def transpose():
- t={i:[] for i in range(v)}
- for i in range(v):
- for j in adj[i]:
- t[j].append(i)
- return t
- def dfs(src,q):
- vis[src]=True
- for i in adj[src]:
- if vis[i]==False:
- dfs(i,q)
- q.append(src)
- def ndfs(src):
- vis[src]=True
- for i in tran[src]:
- if vis[i]==False:
- ndfs(i)
- q=deque()
- vis=[False for i in range(v)]
- for i in range(v):
- if vis[i]==False:
- dfs(i,q)
- for i in range(v):
- vis[i]=False
- tran={}
- tran=transpose()
- count=0
- while q:
- t=q.pop()
- if vis[t]==False:
- count+=1
- ndfs(t)
- return count
- #{
- # Driver Code Starts
- #Initial Template for Python 3
- from collections import OrderedDict
- import sys
- sys.setrecursionlimit(10**6)
- if __name__ == '__main__':
- t = int(input())
- for i in range(t):
- V,E = list(map(int, input().strip().split()))
- adj = [[] for i in range(V)]
- for i in range(E):
- a,b = map(int,input().strip().split())
- adj[a].append(b)
- ob = Solution()
- print(ob.kosaraju(V, adj))
- # } Driver Code Ends
Add Comment
Please, Sign In to add comment