Skip to content

Commit b7de63e

Browse files
authored
Merge pull request #132 from devarakondapranav/master
added graph algorithm
2 parents e41cffb + 7f18c9b commit b7de63e

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'''
2+
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+
class Graph:
9+
def __init__(self, nnodes, nedges):
10+
self.nnodes = nnodes
11+
self.nedges = nedges
12+
self.adj = []
13+
for i in range(nnodes+1):
14+
temp = []
15+
for j in range(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+
def addEdge(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
27+
def dfsHelper(self, v, visited, myval, parent, parents):
28+
29+
30+
parents[v] = parent
31+
#save the parent if this node.
32+
33+
34+
visited[v] = True
35+
#mark this node as detected
36+
37+
for i in range(1, len(self.adj[0])):
38+
39+
if(self.adj[v][i] == 1):
40+
if(visited[i] == False):
41+
self.dfsHelper(i, visited, myval+1, v, parents)
42+
43+
else:
44+
45+
if(i!=parent):
46+
#cycle detected
47+
48+
cur = parent
49+
count =1
50+
#start traversing the parents from here till we reach the current node again
51+
while(cur!=i):
52+
cur = parents[cur]
53+
54+
count+=1
55+
if(count>self.nedges):
56+
break
57+
58+
#save count which is the length of the cycle.
59+
if(count <self.nedges):
60+
self.cyclens.append(count+1)
61+
62+
visited[i] = True
63+
64+
65+
66+
#wrapper function to call the above helper function.
67+
def dfs(self, v):
68+
visited = [0 for i in range(self.nnodes+1)]
69+
self.cyclens = []
70+
parents = [0]*(self.nnodes+1)
71+
self.dfsHelper(v, visited, 1, 0, parents)
72+
print(sum(self.cyclens))

0 commit comments

Comments
 (0)