Skip to content

Commit 0cf4bd6

Browse files
authored
Create floyd_warshall.py
Created a new graph algorithm (floyd warshall's algorithm)
1 parent 13e4d3e commit 0cf4bd6

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

graphs/floyd_warshall.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
Author:- Sanjay Muthu <https://github.com/XenoBytesX>
3+
4+
The Algorithm:
5+
The Floyd Warshall algorithm is a All Pairs Shortest Path algorithm (APSP)
6+
which finds the shortest path between all the pairs of nodes.
7+
8+
Complexity:
9+
Time Complexity:- O(n^3)
10+
Space Complexity:- O(n^2)
11+
12+
Wiki page:- <https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm>
13+
"""
14+
15+
def floyd_warshall(graph, n):
16+
"""
17+
Returns the shortest distance between all pairs of nodes
18+
19+
>>> floyd_warshall(G1, 6)
20+
[\
21+
[0, 2, 4, 5, 6, 3], \
22+
[2, 0, 2, 3, 4, 5], \
23+
[4, 2, 0, 1, 2, 7], \
24+
[5, 3, 1, 0, 1, 6], \
25+
[6, 4, 2, 1, 0, 5], \
26+
[3, 5, 7, 6, 5, 0]\
27+
]
28+
"""
29+
# The graph is a Adjancecy matrix (see <https://en.wikipedia.org/wiki/Adjacency_matrix>)
30+
distance: list[list] = graph
31+
for k in range(n):
32+
for i in range(n):
33+
for j in range(n):
34+
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
35+
return distance
36+
37+
if __name__ == '__main__':
38+
INF = 999999
39+
G1 = [
40+
[0, 2, INF, INF, INF, 3],
41+
[2, 0, 2, INF, INF, INF],
42+
[INF, 2, 0, 1, INF, INF],
43+
[INF, INF, 1, 0, 1, INF],
44+
[INF, INF, INF, 1, 0, 5],
45+
[3, INF, INF, INF, 5, 0]
46+
]
47+
"""
48+
Layout of G1:-
49+
2 2 1 1 5
50+
(1) <-----> (2) <-----> (3) <-----> (4) <-----> (5) <-----> (6)
51+
/\\ /\\
52+
|| ||
53+
--------------------------------------------------------------
54+
3
55+
"""
56+
57+
import doctest
58+
59+
doctest.testmod()

0 commit comments

Comments
 (0)