![]() |
VOOZH | about |
The Bellman-Ford algorithm is a single-source shortest-path algorithm that works by iteratively relaxing edges in the graph until the shortest path to all vertices is found. It is especially useful for graphs with negative edge weights, as it can detect negative cycles and return a suitable error message.
The Floyd-Warshall algorithm is a multi-source shortest path algorithm that works by computing the shortest path between all pairs of vertices in the graph using dynamic programming. It is known for its simplicity and ease of implementation, making it a popular choice in many applications.
In this article, we will compare and contrast the Bellman-Ford algorithm and the Floyd-Warshall algorithm, examining their respective strengths and weaknesses, time and space complexity, and implementation details.
As we know that both of these algorithms work on Directed Graphs, Let us take a common example to understand the approaches of these algorithms.
The Bellman-Ford algorithm can be implemented as follows:
- Initialize the distance from the source vertex (i.e. 0) to all other vertices in the graph to infinity, except for the distance from the source vertex to itself, which is 0.
- For each vertex in the graph, repeat the following process |V|-1 times (where |V| is the number of vertices in the graph):
- For each edge (u, v) in the graph, where u is the source vertex and v is the destination vertex, relax the edge by updating the distance to v if the distance to u plus the weight of (u, v) is less than the current distance to v.
- After the (|V|-1)th iteration, check for the presence of negative cycles by iterating over all the edges in the graph and checking if any of them can still be relaxed. If so, then a negative cycle is present, and the algorithm returns a suitable error message.
Here's how the algorithm would work:
Hence our distance from source 0 to each node will look like this,
The shortest distances from 0 to 0 ---> 0 0 to 1 ---> 2 0 to 2 ---> 4 0 to 3 ---> 4 0 to 4 ---> 3 0 to 5 ---> 5
Time complexity: O(|V||E|)
Auxiliary space: O(|V|)
The Floyd-Warshall algorithm is used to find the shortest path between all pairs of nodes in a weighted graph. It works by maintaining a distance matrix where each entry (i, j) represents the shortest distance from node i to node j. The algorithm starts by initializing the distance matrix with the weights of the edges in the graph. Then, it iteratively updates the distance matrix by considering all possible intermediate nodes and choosing the path with the minimum total weight.
0 2 4 4 3 5 3 0 2 2 3 3 -1 -1 0 1 2 1 -1 -1 -1 0 1 -1 -1 -1 -1 2 0 -1 -1 -1 -1 -1 -1 0
Time complexity: O(N^3)
Auxiliary Space: O(N^2)