Floyd-Warshall Algorithm in C
Last Updated :
17 Jul, 2024
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 about the working of the Floyd-Warshall algorithm, how to implement the Floyd-Warshall algorithm in C, and its applications.
Floyd-Warshall Algorithm for All-Pairs Shortest Paths in C
The Floyd-Warshall Algorithm is a dynamic programming algorithm used to find the shortest paths between all pairs of vertices in a given weighted graph. It systematically updates the solution matrix to ensure that it eventually contains the shortest paths between all pairs of vertices.
Principle of Floyd-Warshall Algorithm
The principle behind the Floyd-Warshall algorithm is to use a matrix to keep track of the shortest paths between all pairs of vertices. The algorithm iteratively updates this matrix by considering each vertex as an intermediate point and checking if a shorter path exists through that vertex.
Floyd-Warshall Algorithm in C Language
The key idea is to improve the distance between any two vertices (i, j) by considering an intermediate vertex k. If the distance from i to j through k is shorter than the current known distance, update the distance.
Floyd Warshall AlgorithmBelow is the algorithm for finding the shortest paths between all pairs of vertices using the Floyd-Warshall algorithm:
- Create a matrix dist[][] initialized with the input graph's weights. If there is no edge between vertices i and j, set dist[i][j] to infinity (or a large value).
- For each pair of vertices (i, j), update dist[i][j] by considering each vertex k as an intermediate point. The update rule is:
- if (dist[i][k] + dist[k][j] < dist[i][j])
- dist[i][j] = dist[i][k] + dist[k][j];
- Repeat the update step for all vertices k as intermediates to ensure all possible paths are considered.
Working of Floyd-Warshall Algorithm
Let us 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 to Implement Floyd Warshall Algorithm
The below program demonstrates how we can implement floyd warshall algorithm in C language.
C
// C Program for Floyd Warshall Algorithm
#include <stdio.h>
// Number of vertices in the graph
#define V 4
/* Define Infinite as a large enough
value. This value will be used
for vertices not connected to each other */
#define INF 99999
// A function to print the solution matrix
void printSolution(int dist[][V]);
// Solves the all-pairs shortest path
// problem using Floyd Warshall algorithm
void floydWarshall(int dist[][V])
{
int i, j, k;
/* Add all vertices one by one to
the set of intermediate vertices.
---> Before start of an iteration, we
have shortest distances between all
pairs of vertices such that the shortest
distances consider only the
vertices in set {0, 1, 2, .. k-1} as
intermediate vertices.
----> After the end of an iteration,
vertex no. k is added to the set of
intermediate vertices and the set
becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (i = 0; i < V; i++) {
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++) {
// If vertex k is on the shortest path from
// i to j, then update the value of
// dist[i][j]
if (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);
}
/* A utility function to print solution */
void printSolution(int dist[][V])
{
printf(
"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)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}
// driver's code
int main()
{
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3 */
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };
// Function call
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
The Floyd-Warshall algorithm is used in various applications:
- To find the shortest paths in computer networks.
- To compute the transitive closure of a graph.
- For graphs where we need to find the shortest path between every pair of vertices.
- To determine the shortest paths in transportation networks.
- To find the shortest paths in game maps and terrains.
Related Articles
You can also go through the following related articles on floyd-warshall algorithms:
Similar Reads
Floyd-Warshall Algorithm in C++
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 n
4 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 eve
6 min read
Prim's Algorithm in C++
Prim's Algorithm is a greedy algorithm that is used to find the Minimum Spanning Tree (MST) for a weighted, undirected graph. MST is a subset of the graph's edges that connects all vertices together without any cycles and with the minimum possible total edge weight In this article, we will learn the
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,
4 min read
Prim's Algorithm in C
Primâs algorithm is a greedy algorithm that finds the minimum spanning tree (MST) for a weighted undirected graph. It starts with a single vertex and grows the MST one edge at a time by adding the smallest edge that connects a vertex in the MST to a vertex outside the MST. In this article, we will l
6 min read
Kosarajuâs Algorithm in C
Kosarajuâs Algorithm is a method by which we can use to find all strongly connected components (SCCs) in a directed graph. This algorithm has application in various applications such as finding cycles in a graph, understanding the structure of the web, and analyzing networks. In this article, we wil
5 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 oth
4 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
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