imashutosh51

Detect the cycle in undirected graph using BFS

Mar 22nd, 2026 (edited)
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. '''
  2. Same approach like dfs but storing the node and parent in the q
  3. '''
  4.  
  5. from collections import defaultdict, deque
  6. class Solution:
  7.     def isCycle(self, V, edges):
  8.         adj = defaultdict(list)
  9.         visited = [False] * V
  10.        
  11.         for u, v in edges:
  12.             adj[u].append(v)
  13.             adj[v].append(u)
  14.        
  15.         for i in range(V):   # This loop is needed when the graph is not connected
  16.             if not visited[i]:
  17.                 q = deque([])
  18.                 q.append([i, -1])
  19.                 visited[i] = True
  20.                
  21.                 while q:
  22.                     temp = q.popleft()
  23.                    
  24.                     for neigh in adj[temp[0]]:
  25.                         if visited[neigh] == True and neigh != temp[1]:
  26.                             return True
  27.                         elif visited[neigh] == False:
  28.                             q.append([neigh, temp[0]])
  29.                             visited[neigh] = True
  30.        
  31.         return False
  32.                            
Advertisement
Add Comment
Please, Sign In to add comment