Floyd Warshall Algorithm
The Floyd Warshall Algorithm is an all-pair shortest path algorithm that uses Dynamic Programming to find the shortest distances between every pair of vertices in a graph, unlike Dijkstra and Bellman-Ford which are single source shortest path algorithms. This algorithm works for both the directed and undirected weighted graphs and can handle graphs with both positive and negative weight edges.
Note: It does not work for the graphs with negative cycles (where the sum of the edges in a cycle is negative).
Idea Behind Floyd Warshall Algorithm:
Suppose we have a graph graph[][] with V vertices from 0to V-1. Now we have to evaluate a dist[][] where dist[i][j] represents the shortest path between vertex i to j.
Let us assume that vertices i to j have intermediate nodes. The idea behind Floyd Warshall algorithm is to treat each and every vertex k from 0 to V-1 as an intermediate node one by one. When we consider the vertex k, we must have considered vertices from 0 to k-1 already. So we use the shortest paths built by previous vertices to build shorter paths with vertex k included.
The following figure shows the above optimal substructure property in Floyd Warshall algorithm:
Algorithm
- Initialize the solution matrix same as the input graph matrix as a first step.
- Then update the solution matrix by considering all vertices as an intermediate vertex.
- The idea is to pick all vertices one by one and updates all shortest paths which include the picked vertex as an intermediate vertex in the shortest path.
- When we pick vertex number k as an intermediate vertex, we already have considered vertices {0, 1, 2, .. k-1} as intermediate vertices.
- For every pair (i, j) of the source and destination vertices respectively, there are two possible cases.
- k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j] as it is.
- k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as dist[i][k] + dist[k][j], if dist[i][j] > dist[i][k] + dist[k][j]
Illustration:
















Note : In the below implementation, we have not created a separate dist[][] matrix. We have modified the input graph matrix to store our final result to keep the implementation simple. Users can easily modify it to initialize dist[][] as a copy of graph[][]. Also, we have used -1 value to indicate no edge between two vertices instead of infinite to keep the implementation simple.
// C++ Program for Floyd Warshall Algorithm
#include <bits/stdc++.h>
using namespace std;
// Solves the all-pairs shortest path
// problem using Floyd Warshall algorithm
void floydWarshall(vector<vector<int>> &graph) {
int V = graph.size();
// Add all vertices one by one to
// the set of intermediate vertices.
for (int k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
// Pick all vertices as destination
// for the above picked source
for (int j = 0; j < V; j++) {
// If vertex k is on the shortest path from
// i to j, then update the value of graph[i][j]
if ((graph[i][j] == -1 ||
graph[i][j] > (graph[i][k] + graph[k][j]))
&& (graph[k][j] != -1 && graph[i][k] != -1))
graph[i][j] = graph[i][k] + graph[k][j];
}
}
}
}
int main() {
vector<vector<int>> graph = {
{0, 4, -1, 5, -1},
{-1, 0, 1, -1, 6},
{2, -1, 0, 3, -1},
{-1, -1, 1, 0, 2},
{1, -1, -1, 4, 0}
};
floydWarshall(graph);
for(int i = 0; i<graph.size(); i++) {
for(int j = 0; j<graph.size(); j++) {
cout<<graph[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
// Java Program for Floyd Warshall Algorithm
import java.util.*;
class GfG {
// Solves the all-pairs shortest path
// problem using Floyd Warshall algorithm
static void floydWarshall(int[][] graph) {
int V = graph.length;
// Add all vertices one by one to
// the set of intermediate vertices.
for (int k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
// Pick all vertices as destination
// for the above picked source
for (int j = 0; j < V; j++) {
// If vertex k is on the shortest path from
// i to j, then update the value of graph[i][j]
if ((graph[i][j] == -1 ||
graph[i][j] > (graph[i][k] + graph[k][j]))
&& (graph[k][j] != -1 && graph[i][k] != -1))
graph[i][j] = graph[i][k] + graph[k][j];
}
}
}
}
public static void main(String[] args) {
int[][] graph = {
{0, 4, -1, 5, -1},
{-1, 0, 1, -1, 6},
{2, -1, 0, 3, -1},
{-1, -1, 1, 0, 2},
{1, -1, -1, 4, 0}
};
floydWarshall(graph);
for (int i = 0; i < graph.length; i++) {
for (int j = 0; j < graph.length; j++) {
System.out.print(graph[i][j] + " ");
}
System.out.println();
}
}
}
# Python Program for Floyd Warshall Algorithm
# Solves the all-pairs shortest path
# problem using Floyd Warshall algorithm
def floydWarshall(graph):
V = len(graph)
# Add all vertices one by one to
# the set of intermediate vertices.
for k in range(V):
# Pick all vertices as source one by one
for i in range(V):
# Pick all vertices as destination
# for the above picked source
for j in range(V):
# If vertex k is on the shortest path from
# i to j, then update the value of graph[i][j]
if ((graph[i][j] == -1 or
graph[i][j] > (graph[i][k] + graph[k][j]))
and (graph[k][j] != -1 and graph[i][k] != -1)):
graph[i][j] = graph[i][k] + graph[k][j]
if __name__ == "__main__":
graph = [
[0, 4, -1, 5, -1],
[-1, 0, 1, -1, 6],
[2, -1, 0, 3, -1],
[-1, -1, 1, 0, 2],
[1, -1, -1, 4, 0]
]
floydWarshall(graph)
for i in range(len(graph)):
for j in range(len(graph)):
print(graph[i][j], end=" ")
print()
// C# Program for Floyd Warshall Algorithm
using System;
class GfG {
// Solves the all-pairs shortest path
// problem using Floyd Warshall algorithm
static void floydWarshall(int[,] graph) {
int V = graph.GetLength(0);
// Add all vertices one by one to
// the set of intermediate vertices.
for (int k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
// Pick all vertices as destination
// for the above picked source
for (int j = 0; j < V; j++) {
// If vertex k is on the shortest path from
// i to j, then update the value of graph[i,j]
if ((graph[i, j] == -1 ||
graph[i, j] > (graph[i, k] + graph[k, j]))
&& (graph[k, j] != -1 && graph[i, k] != -1))
graph[i, j] = graph[i, k] + graph[k, j];
}
}
}
}
static void Main() {
int[,] graph = {
{0, 4, -1, 5, -1},
{-1, 0, 1, -1, 6},
{2, -1, 0, 3, -1},
{-1, -1, 1, 0, 2},
{1, -1, -1, 4, 0}
};
floydWarshall(graph);
for (int i = 0; i < graph.GetLength(0); i++) {
for (int j = 0; j < graph.GetLength(1); j++) {
Console.Write(graph[i, j] + " ");
}
Console.WriteLine();
}
}
}
// JavaScript Program for Floyd Warshall Algorithm
// Solves the all-pairs shortest path
// problem using Floyd Warshall algorithm
function floydWarshall(graph) {
let V = graph.length;
// Add all vertices one by one to
// the set of intermediate vertices.
for (let k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (let i = 0; i < V; i++) {
// Pick all vertices as destination
// for the above picked source
for (let j = 0; j < V; j++) {
// If vertex k is on the shortest path from
// i to j, then update the value of graph[i][j]
if ((graph[i][j] === -1 ||
graph[i][j] > (graph[i][k] + graph[k][j]))
&& (graph[k][j] !== -1 && graph[i][k] !== -1))
graph[i][j] = graph[i][k] + graph[k][j];
}
}
}
}
// Driver Code
let graph = [
[0, 4, -1, 5, -1],
[-1, 0, 1, -1, 6],
[2, -1, 0, 3, -1],
[-1, -1, 1, 0, 2],
[1, -1, -1, 4, 0]
];
floydWarshall(graph);
for (let i = 0; i < graph.length; i++) {
console.log(graph[i].join(" "));
}
Output
0 4 5 5 7 3 0 1 4 6 2 6 0 3 5 3 7 1 0 2 1 5 5 4 0
Time Complexity: O(V3), where V is the number of vertices in the graph and we run three nested loops each of size V.
Auxiliary Space: O(V2), to create a 2-D matrix in order to store the shortest distance for each pair of nodes.
Read here for detailed analysis: complexity analysis of the Floyd Warshall algorithm
Note: The above program only prints the shortest distances. We can modify the solution to print the shortest paths also by storing the predecessor information in a separate 2D matrix.
Why Floyd Warshall Works (Correctness Proof)?
The algorithm relies on the principle of optimal substructure, meaning:
- If the shortest path from i to j passes through some vertex k, then the path from i to k and the path from k to j must also be shortest paths.
- The iterative approach ensures that by the time vertex k is considered, all shortest paths using only vertices 0 to k-1 have already been computed.
By the end of the algorithm, all shortest paths are computed optimally because each possible intermediate vertex has been considered.
Why Floyd-Warshall Algorithm better for Dense Graphs and not for Sparse Graphs?
Dense Graph: A graph in which the number of edges are significantly much higher than the number of vertices.
Sparse Graph: A graph in which the number of edges are very much low.No matter how many edges are there in the graph the Floyd Warshall Algorithm runs for O(V3) times therefore it is best suited for Dense graphs. In the case of sparse graphs, Johnson’s Algorithm is more suitable.
Real World Applications of Floyd-Warshall Algorithm
- In computer networking, the algorithm can be used to find the shortest path between all pairs of nodes in a network. This is termed as network routing.
- Flight Connectivity In the aviation industry to find the shortest path between the airports.
- GIS(Geographic Information Systems) applications often involve analyzing spatial data, such as road networks, to find the shortest paths between locations.
- Kleene’s algorithm which is a generalization of floyd warshall, can be used to find regular expression for a regular language.

Important Interview questions related to Floyd-Warshall
- How to Detect Negative Cycle in a graph using Floyd Warshall Algorithm?
- How is Floyd-warshall algorithm different from Dijkstra’s algorithm?
- How is Floyd-warshall algorithm different from Bellman-Ford algorithm?
Problems based on Shortest Path
- Shortest Path in Directed Acyclic Graph
- Shortest path with one curved edge in an undirected Graph
- Minimum Cost Path
- Path with smallest difference between consecutive cells
- Print negative weight cycle in a Directed Graph
- 1st to Kth shortest path lengths in given Graph
- Shortest path in a Binary Maze
- Minimum steps to reach target by a Knight
- Number of ways to reach at destination in shortest time
- Snake and Ladder Problem
- Word Ladder