Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Maintain 3 elements in the visited array, -1 means fresh and never visited, 0 means it is in the loop
- so we should not get any 0 node while visiting and once you are done with the node, make it 1 means all
- the neighbors have been visited.
- '''
- from collections import deque, defaultdict
- def dfs(i,graph,visited):
- visited[i]=0
- for neigh in graph[i]:
- if visited[neigh]==0:
- return True
- if dfs(neigh,graph,visited):
- return True
- visited[i]=1
- return False
- class Solution:
- def isCyclic(self, v, edges):
- graph=defaultdict(list)
- for a,b in edges:
- graph[a].append(b)
- visited=[-1]*v
- for i in range(v):
- if visited[i]==-1:
- if dfs(i,graph,visited):
- return True
- return False
Advertisement
Add Comment
Please, Sign In to add comment