Bellman–Ford Algorithm
Bellman–Ford Algorithm.
When we are dealing with a Graph that has negative weights, Dijkstra's algorithm does not work.
In this case, we need to use another algorithm called the "Bellman-Ford" algorithm.
The Bellman-Ford algorithm computes the shortest distances from a root vertex to all vertices like Dijkstra.
It is a simpler algorithm than Dijkstra; however, the time complexity is O(VE) which is higher than Dijkstra.
For Bellman-Ford, it takes a (number of connections - 1) iterations to find the smallest cost from the root to all vertices.
It iteratively reduces the weight of the connections as new paths are explored.
Here is the step for implementing the Bellman-Ford algorithm.
- Set all the possible vertices to infinity.
- Set the cost of the current node to the current node as 0.
- For all edges or connections, If cost(currentNode) + weight(currentNode, targetNode) < cost(currentNode): cost(targetNode) = cost(currentNode) + weight(currentNode, targetNode)
- Repeat the 3 for the number of (vertices -1)
- If you want to find whether the graph has a negative loop, execute 3.
- If cost(currentNode) + weight(currentNode, targetNode) < cost(currentNode) is true for any node in the graph, then the graph has at least one negative loop.
References:
https://www.javatpoint.com/bellman-ford-algorithm
https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/
https://www.educative.io/answers/what-is-the-bellman-ford-algorithm
Comments
Post a Comment