Floyd-Warshall Algorithm in C++
Last Updated :
05 Aug, 2024
The Floyd-Warshall algorithm is a dynamic programming technique used to find the shortest paths between all pairs of vertices in a weighted graph. This algorithm is particularly useful for graphs with dense connections and can handle both positive and negative edge weights, though it cannot handle negative cycles.
In this article, we will learn about the Floyd-Warshall algorithm and how to implement it in C++ language.
Floyd-Warshall Algorithm for All-Pairs Shortest Paths in C++
The Floyd-Warshall algorithm works by considering all pairs of vertices and updating the shortest paths iteratively. It uses a matrix to represent the distances between each pair of vertices, initially setting the distance to infinity for all pairs except for the diagonal (distance from a vertex to itself), which is set to zero.
Principle of Updating Distances
The algorithm repeatedly updates the shortest distance between two vertices by checking if the distance can be minimized by passing through an intermediate vertex.
- Initialize the distance matrix with given edge weights.
- Set the distance from each vertex to itself as 0.
- For each pair of vertices (i, j), update the distance by considering each vertex k as an intermediate vertex.
- If the distance from i to j through k is less than the current distance from i to j, update the distance.
Floyd Warshall Algorithm0.0Below is the algorithm for finding the shortest paths between all pairs of vertices using the Floyd-Warshall 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]
Working of Floyd-Warshall Algorithm
Consider the below example of a graph and see how Floyd-Warshall algorithm will generate the minimum spanning tree(MST) for it step-by-step:
C++ Program for Implementation of Floyd-Warshall Algorithm
Below is a C++ implementation of the Floyd-Warshall algorithm:
C++
// C++ program to implement Floyd-Warshall algorithm
#include <iostream>
#include <limits.h>
#include <vector>
#define INF INT_MAX
using namespace std;
// Function to print the solution matrix
void printSolution(const vector<vector<int>> &dist)
{
int V = dist.size();
cout << "The following matrix shows the shortest distances"
" between every pair of vertices:\n";
for (int i = 0; i < V; ++i)
{
for (int j = 0; j < V; ++j)
{
if (dist[i][j] == INF)
cout << "INF"
<< "\t";
else
cout << dist[i][j] << "\t";
}
cout << endl;
}
}
// Function to implement the Floyd-Warshall algorithm
void floydWarshall(vector<vector<int>> &graph)
{
int V = graph.size();
vector<vector<int>> dist = graph;
// Update the solution matrix by considering all vertices
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];
}
}
}
// Print the shortest distance matrix
printSolution(dist);
}
int main()
{
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3 */
vector<vector<int>> graph = {{0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0}};
// Function call to implement Floyd-Warshall algorithm
floydWarshall(graph);
return 0;
}
OutputThe following matrix shows the shortest distances between every pair of vertices:
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 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.
Applications of Floyd-Warshall Algorithm
- Floyd-Warshall Algorithm is used in network routing protocols to find the shortest paths between all pairs of nodes.
- Can be used to find the transitive closure of a directed graph.
- Useful in comparing all possible paths in a weighted graph.
- Applied in geographical mapping and urban planning for finding shortest routes.
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read