The Floyd‑Warshall algorithm is a dynamic programming approach used to find the shortest paths between all pairs
of vertices in a weighted graph. It works for graphs with both positive and negative edge weights (provided there are no negative weight cycles) and has a time complexity of
The algorithm maintains a 2D array dist
where:
dist[i][j]
) represents the shortest distance from vertex (i) to vertex (j).Initially, dist[i][j]
is set to the weight of the edge from (i) to (j) if such an edge exists; otherwise, it is set to infinity (often denoted by ) . The diagonal elements are zero since the distance from any vertex to itself is zero.
For each vertex (k) (considered as an intermediate vertex), the algorithm updates the distance between every pair of vertices (i) and (j) using the recurrence relation:
Consider a graph with 4 vertices (0, 1, 2, 3) and the following initial distance matrix:
Initial dist:
There is an edge from 0 to 1 with weight 5.
There is an edge from 0 to 3 with weight 10.
There is an edge from 1 to 2 with weight 3.
There is an edge from 2 to 3 with weight 1.
For (k = 0):
Consider paths going through vertex 0.
No update occurs because vertex 0 is the source for its outgoing edges.
For (k = 1):
Consider paths via vertex 1.
For (k = 2):
Consider paths via vertex 2.
For (k = 3):
Consider paths via vertex 3.
No further improvements are possible.
The final shortest path distance matrix is:
This matrix tells us, for example, that the shortest distance from vertex 0 to vertex 3 is 9.
The Floyd‑Warshall algorithm efficiently computes the shortest paths between every pair of vertices by iteratively considering each vertex as an intermediate point. It is particularly useful for dense graphs or when multiple shortest path queries are needed.
https://drawtocode.vercel.app/problems/floyd-warshall-algorithm
Loading component...
Loading component...
INPUT: dist = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} };
OUTPUT: { { 0 5 8 9 } { INF 0 3 4 } { INF INF 0 1 } { INF INF INF 0 } }
public static void main(String[] args) {
int V = 4;
int[][] dist = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} };
for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}//If End
}//Loop End
}//Loop End
}//Loop End
System.out.println("Shortest distances between every pair of vertices:");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF){
System.out.print("INF ");
}//If End
else {
System.out.print(dist[i][j] + " ");
}//Else End
}//Loop End
System.out.println();
}//Loop End
}//function end
Helper Function is not defined.
static final int INF = 99999;