Floyd Warshall Algorithm (Python) - Dynamic Programming - FavTutor
Floyd Warshall Algorithm (Python) - Dynamic Programming - FavTutor
Programming
May 30, 2021 7 Minutes Read
In this article, we will study what is Floyd Warshall Algorithm in the field of Dynamic Programming. We will also study
the example and the python code with its corresponding output to learn and understand the algorithm. At last, we
will go through the practical real-world application of the Floyd Warshall Algorithm.
Algorithm
We construct a matrix D that gives the length of the shortest path between each pair of nodes.
The algorithm initializes D to L, that is, to the direct distances between nodes. It then does n iterations, after iteration
k, D gives the length of the shortest paths that only use nodes in {1,2….k} as intermediate nodes.
After n iterations, D, therefore, gives the length of shortest paths using any of the nodes in N as an intermediate
node. If Dk represents the matrix D after kth iteration it can be implemented by
1
How Floyd Warshall Algorithm Works (Example)
Creating matrix D0 contains the distance between each node with ‘0’ as an intermediate node.
Updating matrix D1 which contains the distance between each node with ‘1’ as an intermediate node. Update
distance if minimum distance value smaller than existing distance value found.
Here distance (3, 2) is updated from infinity to 35, and distance (4, 2) is updated from infinity to 20 as shown
below.
Updating matrix D2 contains the distance between two nodes with ‘2’ as an intermediate node.
D2 [i , j] = min (Dk-1 [i , j], Dk-1 [i, k] + Dk-1 [k , j])
Update distance if minimum distance value smaller than existing distance value found. Here distance (1, 3) is
updated from infinity to 20, and distance (1, 4) is updated from infinity to 10.
Updating matrix D3 contains the distance between two nodes with ‘3’ as an intermediate node.
Update distance if minimum distance value smaller than existing distance value found. Here distance (2, 1) is
updated from 50 to 45
Updating matrix D4 contains the distance between two nodes with ‘4’ as an intermediate node. Update distance if
minimum distance value smaller than existing distance value found.
Here distance (1, 3) is updated from 20 to 15; distance (2, 1) is updated from 45 to 20, and distance (2, 3) is
updated from 15 to 10
# Algorithm
def floyd(G):
dist = list(map(lambda p: list(map(lambda q: q, p)), G))
Output
0 5 15 10
20 0 10 5
30 35 0 15
15 20 5 0
Time Complexity
There are three loops for computing the shortest path in the graph and each of these loops has constant
complexities. Therefore, due to this, the time complexity of the Floyd Warshall algorithm is O(n3). Also, the space
complexity of the Floyd Warshall algorithm is O(n2).