Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Intuition:
- We are exploring an undirected graph using DFS to check if a cycle exists. Because the graph is undirected, every edge works in both directions so while pushing edge(a,b) in the adjacent direction , push a->b and b->a both.
- for eg we have only edge ie (0,1) so adjacency matrix would be {0->1, 1->0}.
- we will go dfs and the moment we will see any neighbor is having already visited, we will just return the false but there is a problem and the problem when you will go from 0 to 1 then the neighbor of 1 would 0 too which is already visited, so you can't return the False there, so just keep track of the parent and return Cycle only if the neighbor is True and not parent.
- """
- from collections import defaultdict
- def fun(i,parent,graph,visited):
- visited[i]=True
- for k in graph[i]:
- if visited[k]==True and k!=parent:
- return True
- elif visited[k]==False and fun(k,i,graph,visited):
- return True
- return False
- class Solution:
- def isCycle(self, v, edges):
- visited=[False]*v
- graph=defaultdict(list)
- for a,b in edges:
- graph[a].append(b)
- graph[b].append(a)
- for i in range(v):
- if visited[i]==False:
- if fun(i,-1,graph,visited):
- return True
- return False
Advertisement