Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Johnson's algorithm for All-pairs shortest paths
Next article icon

Floyd Warshall Algorithm

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a matrix dist[][] of size n x n, where dist[i][j] represents the weight of the edge from node i to node j. If there is no direct edge, dist[i][j] is set to a large value (e.g., 10⁸) to represent infinity. The diagonal entries dist[i][i] are 0, since the distance from a node to itself is zero. The graph may contain negative edge weights, but it does not contain any negative weight cycles.

Your task is to determine the shortest path distance between all pair of nodes i and j in the graph.

Example:

Input: dist[][] = [[0, 4, 10⁸, 5, 10⁸],
[10⁸, 0, 1, 10⁸, 6],
[2, 10⁸, 0, 3, 10⁸],
[10⁸, 10⁸, 1, 0, 2],
[1, 10⁸, 10⁸, 4, 0]]

5

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]]
Explanation:

1

Each cell dist[i][j] in the output shows the shortest distance from node i to node j, computed by considering all possible intermediate nodes using the Floyd-Warshall algorithm.

Floyd Warshall Algorithm:

The Floyd–Warshall algorithm works by maintaining a two-dimensional array that represents the distances between nodes. Initially, this array is filled using only the direct edges between nodes. Then, the algorithm gradually updates these distances by checking if shorter paths exist through intermediate nodes.

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 dist[][] with V vertices from 0 to 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:

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.

Step-by-step implementation

  • Start by updating the distance matrix by treating each vertex as a possible intermediate node between all pairs of vertices.
  • Iterate through each vertex, one at a time. For each selected vertex k, attempt to improve the shortest paths that pass through it.
  • 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]
  • Repeat this process for each vertex k until all intermediate possibilities have been considered.

Illustration:


C++
#include <iostream> #include <vector> #include <climits> using namespace std;  // Solves the all-pairs shortest path // problem using Floyd Warshall algorithm void floydWarshall(vector<vector<int>> &dist) {     int V = dist.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++) {                  // shortest path from                 // i to j                  if(dist[i][k] != 1e8 && dist[k][j]!= 1e8)                 dist[i][j] = min(dist[i][j],dist[i][k] + dist[k][j]);             }         }     } }  int main() {     int INF = 100000000;     vector<vector<int>> dist = {         {0, 4, INF, 5, INF},         {INF, 0, 1, INF, 6},         {2, INF, 0, 3, INF},         {INF, INF, 1, 0, 2},         {1, INF, INF, 4, 0}     };      floydWarshall(dist);     for(int i = 0; i<dist.size(); i++) {         for(int j = 0; j<dist.size(); j++) {             cout<<dist[i][j]<<" ";         }         cout<<endl;     }     return 0; } 
Java
import java.util.*;  class GfG {      // Solves the all-pairs shortest path     // problem using Floyd Warshall algorithm     static void floydWarshall(int[][] dist){         int V = dist.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++) {                      // shortest path from                     // i to j                      if(dist[i][k] != 1e8 && dist[k][j]!= 1e8)                     dist[i][j] = Math.min(dist[i][j],dist[i][k] + dist[k][j]);                 }             }         }     }      public static void main(String[] args)     {         int INF = 100000000;          int[][] dist = { { 0, 4, INF, 5, INF },                          { INF, 0, 1, INF, 6 },                          { 2, INF, 0, 3, INF },                          { INF, INF, 1, 0, 2 },                          { 1, INF, INF, 4, 0 } };          floydWarshall(dist);         for (int i = 0; i < dist.length; i++) {             for (int j = 0; j < dist.length; j++) {                 System.out.print(dist[i][j] + " ");             }             System.out.println();         }     } } 
Python
# Solves the all-pairs shortest path # problem using Floyd Warshall algorithm def floydWarshall(dist):     V = len(dist)      # 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):                 #shortest path from                 #i to j                  if(dist[i][k] != 100000000 and dist[k][j]!= 100000000):                     dist[i][j] = min(dist[i][j],dist[i][k] + dist[k][j]);  if __name__ == "__main__":          INF = 100000000;     dist = [         [0, 4, INF, 5, INF],         [INF, 0, 1, INF, 6],         [2, INF, 0, 3, INF],         [INF, INF, 1, 0, 2],         [1, INF, INF, 4, 0]     ]          floydWarshall(dist)     for i in range(len(dist)):         for j in range(len(dist)):             print(dist[i][j], end=" ")         print() 
C#
using System;  class GfG {     static void floydWarshall(int[,] dist)     {         int V = dist.GetLength(0);          for (int k = 0; k < V; k++)         {             for (int i = 0; i < V; i++)             {                 for (int j = 0; j < V; j++)                 {                     // shortest path from                     // i to j                  if(dist[i,k] != 1e8 && dist[k, j]!= 1e8)                    dist[i,j] = Math.Min(dist[i, j], dist[i, k] + dist[k, j]);                 }             }         }     }     // large number as "infinity"     const int INF = 100000000;       static void Main()     {         int[,] dist = {             {0, 4, INF, 5, INF},             {INF, 0, 1, INF, 6},             {2, INF, 0, 3, INF},             {INF, INF, 1, 0, 2},             {1, INF, INF, 4, 0}         };          floydWarshall(dist);          for (int i = 0; i < dist.GetLength(0); i++)         {             for (int j = 0; j < dist.GetLength(1); j++)             {                     Console.Write(dist[i, j] + " ");             }             Console.WriteLine();         }     } } 
JavaScript
// Solves the all-pairs shortest path // problem using Floyd Warshall algorithm function floydWarshall(dist) {     let V = dist.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++) {                  // shortest path from                 // i to j                 if (dist[i][k] != INF && dist[k][j] != INF) {                     dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);                 }             }         }     } }  let INF = 100000000;  // Driver Code let dist = [     [0, 4, INF, 5, INF],      [INF, 0, 1, INF, 6],     [2, INF, 0, 3, INF],     [INF, INF, 1, 0, 2],     [1, INF, INF, 4, 0] ];  floydWarshall(dist);  for (let i = 0; i < dist.length; i++) {     console.log(dist[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(1).

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. 

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


Next Article
Johnson's algorithm for All-pairs shortest paths
author
kartik
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • Graph
  • Floyd-Warshall
  • Samsung
  • Shortest Path
Practice Tags :
  • Samsung
  • Dynamic Programming
  • Graph
  • Shortest Path

Similar Reads

  • Graph Algorithms
    Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. BasicsGraph and its representationsBFS and DFS Breadt
    3 min read
  • Introduction to Graph Data Structure
    Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
    15+ min read
  • Graph and its representations
    A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
    12 min read
  • Types of Graphs with Examples
    A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
    9 min read
  • Basic Properties of a Graph
    A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are kn
    4 min read
  • Applications, Advantages and Disadvantages of Graph
    Graph is a non-linear data structure that contains nodes (vertices) and edges. A graph is a collection of set of vertices and edges (formed by connecting two vertices). A graph is defined as G = {V, E} where V is the set of vertices and E is the set of edges. Graphs can be used to model a wide varie
    7 min read
  • Transpose graph
    Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Giv
    9 min read
  • Difference Between Graph and Tree
    Graphs and trees are two fundamental data structures used in computer science to represent relationships between objects. While they share some similarities, they also have distinct differences that make them suitable for different applications. What is Graph?A graph data structure is a collection o
    2 min read
  • BFS and DFS on Graph

    • Breadth First Search or BFS for a Graph
      Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
      15+ min read

    • Depth First Search or DFS for a Graph
      In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
      13 min read

    • Applications, Advantages and Disadvantages of Depth First Search (DFS)
      Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
      4 min read

    • Applications, Advantages and Disadvantages of Breadth First Search (BFS)
      We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
      4 min read

    • Iterative Depth First Traversal of Graph
      Given a directed Graph, the task is to perform Depth First Search of the given graph. Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list. Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pic
      10 min read

    • BFS for Disconnected Graph
      In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
      14 min read

    • Transitive Closure of a Graph using DFS
      Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: Transit
      8 min read

    • Difference between BFS and DFS
      Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS st
      2 min read

    Cycle in a Graph

    • Detect Cycle in a Directed Graph
      Given the number of vertices V and a list of directed edges, determine whether the graph contains a cycle or not. Examples: Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 0 Input: V = 4, edges[][] = [[0, 1], [0, 2
      15+ min read

    • Detect cycle in an undirected graph
      Given an undirected graph, the task is to check if there is a cycle in the given graph. Examples: Input: V = 4, edges[][]= [[0, 1], [0, 2], [1, 2], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0 Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]] Output: falseExplana
      8 min read

    • Detect Cycle in a directed graph using colors
      Given a directed graph represented by the number of vertices V and a list of directed edges, determine whether the graph contains a cycle. Your task is to implement a function that accepts V (number of vertices) and edges (an array of directed edges where each edge is a pair [u, v]), and returns tru
      9 min read

    • Detect a negative cycle in a Graph | (Bellman Ford)
      Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directe
      15+ min read

    • Cycles of length n in an undirected and connected graph
      Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
      10 min read

    • Detecting negative cycle using Floyd Warshall
      We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative. Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some adva
      12 min read

    • Clone a Directed Acyclic Graph
      A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
      12 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences