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
Floyd-Warshall Algorithm in C 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 and can handle negative weights, provided there are no negative weight cycles.In this article, we will learn
5 min read
Floyd-Warshall Algorithm in Python The Floyd-Warshall algorithm, named after its creators Robert Floyd and Stephen Warshall, is fundamental in computer science and graph theory. It is used to find the shortest paths between all pairs of nodes in a weighted graph. This algorithm is highly efficient and can handle graphs with both posi
3 min read
Tarjanâs Algorithm in C++ In this post, we will see the implementation of Tarjanâs Algorithm in C++ language.What is Tarjanâs Algorithm?Tarjanâs Algorithm is a well-known algorithm used for finding strongly connected components (SCCs) in a directed graph. An SCC is a maximal subgraph where every vertex is reachable from ever
6 min read
Kahnâs Algorithm in C++ In this post, we will see the implementation of Kahnâs Algorithm in C++.What is Kahnâs Algorithm?Kahnâs Algorithm is a classic algorithm used for topological sorting of a directed acyclic graph (DAG). Topological sorting is a linear ordering of vertices such that for every directed edge u -> v, v
4 min read
Kosarajuâs Algorithm in C++ In this post, we will see the implementation of Kosarajuâs Algorithm in C++.What is Kosarajuâs Algorithm?Kosarajuâs Algorithm is a classic algorithm used for finding strongly connected components (SCCs) in a directed graph. An SCC is a maximal subgraph where every vertex is reachable from every othe
4 min read
Convex Hull Algorithm in C++ The Convex Hull problem is fundamental problem in computational geometry. In this, we need to find the smallest convex polygon, known as the convex hull, that can include a given set of points in a two-dimensional plane. This problem has various applications in areas such as computer graphics, geogr
15+ min read
Bellman Ford Algorithm in C++ The Bellman-Ford algorithm is a single-source shortest path algorithm that finds the shortest path from a given source vertex to all other vertices in a graph. Unlike Dijkstraâs algorithm, Bellman-Ford can handle graphs with negative edge weights, making it useful in various scenarios. In this artic
5 min read
Bellman-Ford Algorithm in C The Bellman-Ford algorithm helps find the shortest path from one starting point to all other points in a graph, even if some paths have negative weights. It's useful for network routing problems. In this article, we will learn about the Bellman-Ford algorithm and how to implement it in C. The Bellma
4 min read
Johnson Algorithm in C++ Johnsonâs Algorithm is an algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It is especially useful for sparse graphs and can handle negative weights, provided there are no negative weight cycles. This algorithm uses both Bellman-Ford and Dijkstra's algorit
8 min read
Johnson Algorithm in C Johnson's Algorithm is an efficient algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It works even for graphs with negative weights, provided there are no negative weight cycles. This algorithm is particularly useful for sparse graphs and combines both Dij
5 min read