forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsame_path.py
More file actions
80 lines (60 loc) · 2.3 KB
/
same_path.py
File metadata and controls
80 lines (60 loc) · 2.3 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
Check if two nodes are on the same path in a tree. Use DFS and the concept of intime and outtime.
Intime - time when a node is visited for the first time
Outtime - time when a node is visited for the second time after all its children have been visited
For any pair of node if they are on the same path -
intime[u] < intime[v] and outtime[u] > outtime[v]
"""
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.vertices = vertices
self.intime = None
self.outtime = None
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def dfs(self):
visited = [False] * self.vertices
intime = [0] * self.vertices
outtime = [0] * self.vertices
timer = 0
num_children_visited = [0] * self.vertices
for s in range(self.vertices):
if not visited[s]:
visited[s] = True
stack = []
stack.append(s)
while stack:
s = stack.pop()
timer += 1
intime[s] = timer
for i in self.graph[s]:
if visited[i] == False:
stack.append(i)
visited[i] = True
num_children_visited[s] += 1
if num_children_visited[i] == len(self.graph[i]):
timer += 1
outtime[i] = timer
print('intime - ', intime)
print('outtime - ', outtime)
print('num_children_visited - ', num_children_visited)
self.intime = intime
self.outtime = outtime
def check_same_path(self, u, v):
if (self.intime[u] < self.intime[v] and self.outtime[u] > self.outtime[v]) or \
(self.intime[v] < self.intime[u] and self.outtime[v] > self.outtime[u]):
return True
return False
g = Graph(7)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(0, 3)
g.add_edge(1, 4)
g.add_edge(2, 5)
g.add_edge(3, 6)
g.dfs()
print('Same path - ', g.check_same_path(0, 6))
print(g.graph[6])