Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Acyclic directed graph is needed for the toplogical sort ie. DAG
- you can apply the topo sort on it and if the topo sort is having the same number of
- the vertices in the graph, it means no cycle else there is the cycle.
- You need not to store the full topo sort order, you can store the count also when indegree ==0
- If cycle exists, there will be some node whose indegree will never be 0 so it will not pushed to the deque and because of that the vertices connecting them will not be processed.
- '''
- from collections import deque, defaultdict
- class Solution:
- def isCyclic(self, v, edges):
- graph=defaultdict(list)
- indegree=[0]*v
- for a,b in edges:
- graph[a].append(b)
- indegree[b]+=1
- cnt=0
- q=deque([])
- for i in range(v):
- if indegree[i]==0:
- q.append(i)
- cnt+=1
- while q:
- k=len(q)
- for i in range(k):
- temp=q.popleft()
- # cnt+=1
- for neigh in graph[temp]:
- indegree[neigh]-=1
- if indegree[neigh]==0:
- q.append(neigh)
- cnt+=1
- if cnt!=v:
- return True
- else:
- return False
Advertisement