Path-Relaxation Property
In shortest paths algorithms like Bellman-Ford, the path-relaxation property states that:
If there is a shortest path from u to v that contains edge (x,y), then dist[v] <= dist[x] + weight(x,y).
That is, the shortest path distance to v is bounded by the distance of the preceding vertex plus the edge weight.
This key property leads to an iterative relaxation algorithm:
Java example:
|
|
C++ example:
|
|
Python example:
|
|
Path relaxation is the key optimal substructure enabling shortest path algorithms.
Path-relaxation property is crucial in understanding shortest-path algorithms like Dijkstra’s and Bellman-Ford. It involves “relaxing” the edges, i.e., updating the shortest-path estimate for vertices if a shorter path is found. A single relaxation step for an edge ( (u, v) ) tries to improve the shortest-path estimate from ( u ) to ( v ) using the path through ( u ).
Algorithm
- Initialization: We initialize the distance of all vertices to
infinity
except the source vertex, which is set to0
. - Relaxation: For an edge ( (u, v) ) with weight ( w(u, v) ), if ( dist[u] + w(u, v) < dist[v] ), we update ( dist[v] ).
Java Code
|
|
C++ Code
|
|
Python Code
|
|
In each of these code snippets, dist
is an array storing the shortest-path estimates, graph
is a 2D array representing the weighted graph, and ( (u, v) ) represents an edge from vertex ( u ) to ( v ). The function relax
updates the shortest-path estimate for vertex ( v ) if a shorter path through ( u ) is found.