-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathdetect_cycle_directed_graph
53 lines (45 loc) · 1.24 KB
/
detect_cycle_directed_graph
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Graph:
def __init__(self, v):
# No. of vertices of graph
self.v = v
# Adjacency List
self.adj = [0] * v
for i in range(self.v):
self.adj[i] = []
def addedge(self, i,j):
self.adj[i].append(j)
def isCyclic(self):
visited = [False] * self.v
helper = [False] * self.v
for i in range(self.v):
if visited[i] == False:
ans = self.DFS(i,visited,helper)
if ans == True:
return True
return False
def DFS(self,i, visited,helper):
visited[i] = True
helper[i] = True
neighbours = self.adj[i]
for k in range(len(neighbours)):
curr = neighbours[k]
if helper[curr] == True:
return True
if visited[curr] == False:
ans = self.DFS(curr,visited,helper)
if ans == True:
return True
helper[i] = False
return False
if __name__ == "__main__":
# No of nodes
n = 4
g = Graph(n)
g.addedge(0, 1)
g.addedge(3, 1)
g.addedge(1, 2)
g.addedge(0, 3)
if g.isCyclic() == 1:
print("Graph has a cycle")
else:
print("Graph has no cycle")