Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Same approach like dfs but storing the node and parent in the q
- '''
- from collections import defaultdict, deque
- class Solution:
- def isCycle(self, V, edges):
- adj = defaultdict(list)
- visited = [False] * V
- for u, v in edges:
- adj[u].append(v)
- adj[v].append(u)
- for i in range(V): # This loop is needed when the graph is not connected
- if not visited[i]:
- q = deque([])
- q.append([i, -1])
- visited[i] = True
- while q:
- temp = q.popleft()
- for neigh in adj[temp[0]]:
- if visited[neigh] == True and neigh != temp[1]:
- return True
- elif visited[neigh] == False:
- q.append([neigh, temp[0]])
- visited[neigh] = True
- return False
Advertisement
Add Comment
Please, Sign In to add comment