-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.py
46 lines (36 loc) · 960 Bytes
/
solver.py
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
class Node(object):
def __init__(self, vertex):
self.vertex = vertex
self.edges = []
def add_edge(self, edge):
self.edges.append(edge)
edge.edges.append(self)
#
# Time complexity: O(n) (every node is visited at most once)
# Space complexity: O(n) (stack to define the traversal path)
#
def has_cycle(vertices):
visited = set()
for v in vertices:
# Vertice was already visited by another node,
# so we can skip
if v in visited:
continue
if helper(v, visited):
return True
return False
def helper(root, visited):
stack = [[root, None]] # Pair "[node, parent]"
while stack:
node, parent = stack.pop()
# Visit the node
visited.add(node)
# Schedule the visit for all non-visited edges
for edge in node.edges:
if edge in visited:
if edge is not parent:
# Found a cycle
return True
else:
stack.append([edge, node])
return False