You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If a node is visited again in DFS it means there is a cycle. To get the length of that cycle, we save the parent of current node at every stage of that DFS.
3
+
4
+
Once a visited node is detected again, from this node go its parent and from there to its parent and so on till we reach the first node again. We keep track of how many nodes we have traversed in this process and that will be the length of the cycle.
5
+
'''
6
+
7
+
8
+
classGraph:
9
+
def__init__(self, nnodes, nedges):
10
+
self.nnodes=nnodes
11
+
self.nedges=nedges
12
+
self.adj= []
13
+
foriinrange(nnodes+1):
14
+
temp= []
15
+
forjinrange(nnodes+1):
16
+
temp.append(0)
17
+
self.adj.append(temp)
18
+
self.cyclens= []
19
+
#cyclens will save the length of all cycles
20
+
21
+
defaddEdge(self, a, b):
22
+
self.adj[a][b] =1
23
+
self.adj[b][a] =1
24
+
25
+
26
+
#function to perform dfs and simultaneously calculate lengths of cycles in the graph
0 commit comments