Skip to content

Commit 63b5a54

Browse files
vaibhav4595jainaman224
authored andcommitted
In Reference to jainaman224#159, Python implementation for Floyd Warshall added (jainaman224#255)
1 parent 15d93ae commit 63b5a54

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class FloydWarshall:
2+
"""
3+
Implements : Floyd Warshall Algorithm
4+
Inputs : Adjaceny Matrix (list of lists)
5+
Outputs : Shortest distance between all pairs
6+
"""
7+
8+
def __init__(self, adj_matrix):
9+
"""
10+
Initialises distance matrix (list of lists)
11+
"""
12+
13+
self.adj_matrix = adj_matrix
14+
self.distance = adj_matrix
15+
self.num_vertices = len(adj_matrix)
16+
17+
def run(self):
18+
""""
19+
Implements Floyd Warshall Algorithm
20+
"""
21+
22+
for k in xrange(0, self.num_vertices):
23+
for i in xrange(0, self.num_vertices):
24+
for j in xrange(0, self.num_vertices):
25+
if self.distance[i][k] + self.distance[k][j] < self.distance[i][j]:
26+
self.distance[i][j] = self.distance[i][k] + self.distance[k][j]
27+
28+
def get_distance(self):
29+
"""
30+
Returns the distance list
31+
"""
32+
33+
return self.distance
34+
35+
def print_distance(self):
36+
for node in self.distance:
37+
for each in node:
38+
print each,
39+
print
40+
41+
def main():
42+
graph = [[0, 5, float('inf'), 10],
43+
[float('inf'), 0, 3, float('inf')],
44+
[float('inf'), float('inf'), 0, 1],
45+
[float('inf'), float('inf'), float('inf'), 0]]
46+
47+
48+
floyd = FloydWarshall(graph)
49+
floyd.run()
50+
floyd.print_distance()
51+
52+
if __name__ == '__main__':
53+
main()
54+
55+
#OUTPUT
56+
#0 5 8 9
57+
#inf 0 3 4
58+
#inf inf 0 1
59+
#inf inf inf 0

0 commit comments

Comments
 (0)