imashutosh51

Detect a cycle in directed graph using DFS

Mar 22nd, 2026
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. '''
  2. Maintain 3 elements in the visited array, -1 means fresh and never visited, 0 means it is in the loop
  3. so we should not get any 0 node while visiting and once you are done with the node, make it 1 means all
  4. the neighbors have been visited.
  5. '''
  6. from collections import deque, defaultdict
  7. def dfs(i,graph,visited):
  8.     visited[i]=0
  9.     for neigh in graph[i]:
  10.         if visited[neigh]==0:
  11.             return True
  12.         if dfs(neigh,graph,visited):
  13.             return True
  14.     visited[i]=1
  15.     return False
  16.        
  17. class Solution:
  18.     def isCyclic(self, v, edges):
  19.         graph=defaultdict(list)
  20.         for a,b in edges:
  21.             graph[a].append(b)
  22.         visited=[-1]*v
  23.         for i in range(v):
  24.             if visited[i]==-1:
  25.                 if dfs(i,graph,visited):
  26.                     return True
  27.         return False
Advertisement
Add Comment
Please, Sign In to add comment