Bellman–Ford single source shortest path algorithm
Given a graph and a source
vertex src in graph, find shortest paths from src to
all vertices in the given graph. The graph may contain negative weight edges.
Following are the detailed steps.
Input: Graph and a source vertex src
Output: Shortest distance to all vertices from src.
If there is a negative weight cycle, then shortest
distances are not
calculated, negative weight cycle is reported.
1) This step initializes distances from source to all vertices
as infinite and distance to source itself as 0. Create an array dist[] of size
|V| with all values as infinite except dist[src] where src is source vertex.
2) This step calculates shortest distances. Do following
|V|-1 times where |V| is the number of vertices in given graph.
Do following for each edge u-v
If dist[v] > dist[u] + weight of edge uv, then update dist[v]
dist[v] = dist[u] + weight of edge uv
If dist[v] > dist[u] + weight of edge uv, then update dist[v]
dist[v] = dist[u] + weight of edge uv
3) This step reports if there is a negative weight cycle
in graph. Do following for each edge u-v
If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle”
If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle”
The idea of step 3 is, step 2
guarantees shortest distances if graph doesn’t contain negative weight cycle.
If we iterate through all edges one more time and get a shorter path for any
vertex, then there is a negative weight cycle
Example:
In this particular example, we have
5 vertices so there will be |V-1| that is 5-1= 4 passes. Each pass relaxes the
edges in the order
Is the given graph with source node
‘s’ and initialized to 0 and all remaining distances initialized to infinity.
Start with all the ordered edges
and start finding and updating distances
After Pass 4: there
is no updating of distances after pass 4. It is the last pass and the shortest path
is
No comments:
Post a Comment