forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdag_longest_path.py
More file actions
71 lines (47 loc) · 1.59 KB
/
Copy pathdag_longest_path.py
File metadata and controls
71 lines (47 loc) · 1.59 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
"""
The idea is similar to DAG Shortest Path. Only the comparision part changes
"""
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.vertices = vertices
def add_edge(self, u, v, w):
self.graph[u].append((v, w))
def topological_sort_util(self, vertex, visited, stack):
visited[vertex] = True
for v, weight in self.graph[vertex]:
if visited[v] == False:
self.topological_sort_util(v, visited, stack)
stack.insert(0, vertex)
def topological_sort(self):
visited = [False] * self.vertices
stack = []
for v in range(self.vertices):
if visited[v] == False:
self.topological_sort_util(v, visited, stack)
return stack
def longest_path(self, s):
stack = self.topological_sort()
distance = [-float("inf")] * self.vertices
distance[s] = 0
while stack:
i = stack.pop(0)
for vertex, weight in self.graph[i]:
if distance[vertex] < distance[i] + weight:
distance[vertex] = distance[i] + weight
for i in range(self.vertices):
print(f"{s} -> {i} = {distance[i]}")
g = Graph(6)
g.add_edge(0, 1, 5)
g.add_edge(0, 2, 3)
g.add_edge(1, 3, 6)
g.add_edge(1, 2, 2)
g.add_edge(2, 4, 4)
g.add_edge(2, 5, 2)
g.add_edge(2, 3, 7)
g.add_edge(3, 5, 1)
g.add_edge(3, 4, -1)
g.add_edge(4, 5, -2)
source = 0
g.longest_path(source)