Skip to content

Commit b9d42b9

Browse files
committed
Detect Cycle in Directed Graph
1 parent 5eb849d commit b9d42b9

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Author: OMKAR PATHAK
2+
3+
# Time Complexity: O(|V| + |E|)
4+
class Graph():
5+
def __init__(self):
6+
self.vertex = {}
7+
8+
# for printing the Graph vertexes
9+
def printGraph(self):
10+
for i in self.vertex.keys():
11+
print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]]))
12+
13+
# for adding the edge beween two vertexes
14+
def addEdge(self, fromVertex, toVertex):
15+
# check if vertex is already present,
16+
if fromVertex in self.vertex.keys():
17+
self.vertex[fromVertex].append(toVertex)
18+
else:
19+
# else make a new vertex
20+
self.vertex[fromVertex] = [toVertex]
21+
22+
# This function will return True if graph is cyclic else return False
23+
def checkCyclic(self):
24+
visited = [False] * len(self.vertex)
25+
stack = [False] * len(self.vertex)
26+
for vertex in range(len(self.vertex)):
27+
if visited[vertex] == False:
28+
if self.checkCyclicRec(visited, stack, vertex) == True:
29+
return True
30+
return False
31+
32+
# Recursive function for finding the cycle
33+
def checkCyclicRec(self, visited, stack, vertex):
34+
# Mark the current node in visited and also add it to the stack
35+
visited[vertex] = True
36+
stack[vertex] = True
37+
38+
# mark all adjacent nodes of the current node
39+
for adjacentNode in self.vertex[vertex]:
40+
if visited[adjacentNode] == False:
41+
if self.checkCyclicRec(visited, stack, adjacentNode) == True:
42+
return True
43+
elif stack[adjacentNode] == True:
44+
return True
45+
46+
# The node needs to be poped from
47+
# recursion stack before function ends
48+
stack[vertex] = False
49+
return False
50+
51+
if __name__ == '__main__':
52+
graph = Graph()
53+
graph.addEdge(0, 1)
54+
graph.addEdge(0, 2)
55+
graph.addEdge(1, 2)
56+
graph.addEdge(2, 0)
57+
graph.addEdge(2, 3)
58+
graph.addEdge(3, 3)
59+
60+
graph.printGraph()
61+
62+
if graph.checkCyclic() == 1:
63+
print ("Graph has a cycle")
64+
else:
65+
print ("Graph has no cycle")

0 commit comments

Comments
 (0)