Skip to content

Commit f250bd7

Browse files
added Johnson’s algorithm for shortest path
1 parent e5f2d0a commit f250bd7

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
from collections import defaultdict
2+
MAX_INT = float('Inf')
3+
4+
def minDistance(dist, visited):
5+
6+
(minimum, minVertex) = (MAX_INT, 0)
7+
for vertex in range(len(dist)):
8+
if minimum > dist[vertex] and visited[vertex] == False:
9+
(minimum, minVertex) = (dist[vertex], vertex)
10+
11+
return minVertex
12+
13+
def Dijkstra(graph, modifiedGraph, src):
14+
15+
num_vertices = len(graph)
16+
17+
sptSet = defaultdict(lambda : False)
18+
19+
dist = [MAX_INT] * num_vertices
20+
21+
dist[src] = 0
22+
23+
for count in range(num_vertices):
24+
25+
curVertex = minDistance(dist, sptSet)
26+
sptSet[curVertex] = True
27+
28+
for vertex in range(num_vertices):
29+
if ((sptSet[vertex] == False) and
30+
(dist[vertex] > (dist[curVertex] +
31+
modifiedGraph[curVertex][vertex])) and
32+
(graph[curVertex][vertex] != 0)):
33+
34+
dist[vertex] = (dist[curVertex] +
35+
modifiedGraph[curVertex][vertex]);
36+
37+
for vertex in range(num_vertices):
38+
print ('Vertex ' + str(vertex) + ': ' + str(dist[vertex]))
39+
40+
def BellmanFord(edges, graph, num_vertices):
41+
42+
dist = [MAX_INT] * (num_vertices + 1)
43+
dist[num_vertices] = 0
44+
45+
for i in range(num_vertices):
46+
edges.append([num_vertices, i, 0])
47+
48+
for i in range(num_vertices):
49+
for (src, des, weight) in edges:
50+
if((dist[src] != MAX_INT) and
51+
(dist[src] + weight < dist[des])):
52+
dist[des] = dist[src] + weight
53+
54+
return dist[0:num_vertices]
55+
56+
def JohnsonAlgorithm(graph):
57+
58+
edges = []
59+
60+
for i in range(len(graph)):
61+
for j in range(len(graph[i])):
62+
63+
if graph[i][j] != 0:
64+
edges.append([i, j, graph[i][j]])
65+
66+
modifyWeights = BellmanFord(edges, graph, len(graph))
67+
68+
modifiedGraph = [[0 for x in range(len(graph))] for y in
69+
range(len(graph))]
70+
71+
for i in range(len(graph)):
72+
for j in range(len(graph[i])):
73+
74+
if graph[i][j] != 0:
75+
modifiedGraph[i][j] = (graph[i][j] +
76+
modifyWeights[i] - modifyWeights[j]);
77+
78+
print ('Modified Graph: ' + str(modifiedGraph))
79+
80+
for src in range(len(graph)):
81+
print ('\nShortest Distance with vertex ' +
82+
str(src) + ' as the source:\n')
83+
Dijkstra(graph, modifiedGraph, src)
84+
85+
graph = [[0, -5, 2, 3],
86+
[0, 0, 4, 0],
87+
[0, 0, 0, 1],
88+
[0, 0, 0, 0]]
89+
90+
JohnsonAlgorithm(graph)

0 commit comments

Comments
 (0)