-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetect_cycle.py
More file actions
33 lines (31 loc) · 804 Bytes
/
detect_cycle.py
File metadata and controls
33 lines (31 loc) · 804 Bytes
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
def DFS(s):
visited = [False]*(n)
visited[s]=True
stack = []
S = []
stack.append(s)
S.append(s)
while stack:
x = stack.pop(len(stack)-1)
print(x)
for v in range(n):
if L[x][v]:
if v in S: #If visiting vertex is already in S , cycle present...
return True
elif not visited[v]:
visited[v] = True
stack.append(v)
S.append(s)
return False
L = []
n = int(input("Enter n value : "))
print("Enter a adj_matrix :")
for i in range(n):
L.append([])
for j in range(n):
L[i].append(int(input()))
s = int(input("Enter starting vertex : "))
if DFS(s):
print("Present")
else:
print("Not present")