Floyd-Warshall
The Floyd-Warshall algorithm is a dynamic programming algorithm used to find the shortest paths between all pairs of vertices in a weighted graph.
It works for both directed and undirected graphs with positive or negative edge weights (but with no negative cycles).
Here's a simple explanation of the Floyd-Warshall algorithm:
Initialization: Create a distance matrix
dist
wheredist[i][j]
represents the shortest distance from vertexi
to vertexj
. Initialize this matrix with the direct edge weights if there is an edge betweeni
andj
, otherwise, initialize it with a very large value to represent infinity. Also, initialize the diagonal elements to 0 because the shortest distance from a vertex to itself is always 0.Main Algorithm: Iterate over all vertices
k
, and consider all pairs of vertices(i, j)
. For each pair(i, j)
, if vertexk
is on the shortest path fromi
toj
, then update the value ofdist[i][j]
todist[i][k] + dist[k][j]
if it's smaller than the current value ofdist[i][j]
.Final Result: After completing the iterations, the
dist
matrix will contain the shortest distances between all pairs of vertices.
pseudocode:
In this example, graph
represents a directed graph with 4 vertices. undefined
values indicate that there's no direct edge between those vertices.
The function floydWarshall()
returns the shortest distances between all pairs of vertices in the graph.
Last updated