M4_shotestpath
M4_shotestpath
Shortest-paths problem:
• Given a weighted, directed graph G=(V;E) with weight function w: E-> R mapping edges
to real-valued weights.
• The weight w(p) of path p=<v0,v1,….,vk> is the sum of the weights of its constituent
edges:
• A shortest path from vertex u to vertex v is then defined as any path p with weight
The Bellman-Ford algorithm
• The Bellman-Ford algorithm solves the single-source shortest-paths problem in the
general case in which edge weights may be negative.
• Given a weighted, directed graph G = (V;E) with source s and weight function w:E->R,
the Bellman-Ford algorithm returns a boolean value indicating whether or not there is
a negative-weight cycle that is reachable from the source.
• If there is no such cycle, the algorithm produces the shortest paths and their weights.
Complexity analysis:
• The initialization in line 1 takes (V) time
• Each of the |V|- 1 passes over the edges in lines 2–4 takes (E) time
• the for loop of lines 5–7 takes O(E) time.
• The Bellman-Ford algorithm runs in time O(VE)
Dijkstra’s algorithm
• Solves the single-source shortest-paths problem on a weighted, directed graph
G=(V,E) for the case in which all edge weights are nonnegative.
• The algorithm repeatedly selects the vertex u V- S with the minimum shortest-
path estimate, adds u to S, and relaxes all edges leaving u.
• It maintains the min-priority queue Q by calling three priority-queue operations: INSERT (implicit in line
3), EXTRACT-MIN (line 5), and DECREASE-KEY (implicit in RELAX, which is called in line 8).
• The algorithm calls both INSERT and EXTRACT-MIN once per vertex. Because each vertex u V is added
to set S exactly once, each edge in the adjacency list Adj[u] is examined in the for loop of lines 7–8
exactly once during the course of the algorithm.
• CASE-1(Array) • CASE-2(min-heap)
• Since the total number of edges in all the • Each EXTRACT-MIN operation then takes time O(lg V).
adjacency lists is |E|, this for loop iterates a total • As before, there are |V | such operations.
of |E| times, and thus the algorithm calls DECREASE- • The time to build the binary min-heap is O(V).
KEY at most |E| times overall. • Each DECREASE-KEY operation takes time O(lgV), and
• store v.d in the v th entry of an array. Each INSERT and there are still at most |E| such operations.
DECREASE-KEY operation takes O(1) time, and each • The total running time is therefore O((V +E) lgV), which
EXTRACT-MIN operation takes O(V) time, for a total is O(E lgV) if all vertices are reachable from the source.
time of O(V2 + E)= O(V 2). • This running time improves upon the straightforward
• O(V 2)-time implementation if E = o(V 2/ lgV).
• CASE-3(Fibonacci Heap):
• The amortized cost of each of the |V | EXTRACT-MIN operations is O(lgV), and each DECREASEKEY call,
of which there are at most |E|, takes only O(1) amortized timeheaps.
• The total running time of the algorithm is O(V log V +E)