Algorithms: Single-Source Shortest Path
Algorithms: Single-Source Shortest Path
Lecture 10
Single-Source Shortest Path
Made By :
Mohamed Hegazy
#AC_Committee
Lec 10 Algorithms
How to search in an algorithm
Until now we have studied
How to reach all elements with minimum cost
Shortest-Path problems
Single-pair
Single-source All-pairs
(single- اقصر مسافة بين رأسين اقصر مسافة بين كل
destination)
Solution to single- الVertices زوج من
source problem solves
اقصر مسافة بين this problem efficiently, Dynamic
المصدر وكل رأس too. programming
algorithm
Lec 10 Algorithms
NEGATIVE WEIGHTS AND CYCLES?
- Negative edges are OK, as long as there are no negative weight cycles
" الن ده هيسبب تناقص متتالي للقيمة "كأننا بنرجع بالزمنnegative weight cycles يعني مينفعش يكون
عندنا
- Shortest-paths can have no cycles ولو كانت موجودة بنحسن الناتج باننا نحذفها
- Any shortest-path in graph G can be no longer than n – 1 edges, where n is the number
of vertices
RELAXATION:
- Relaxing an edge (u, v) means testing whether we can improve the shortest path to v
found so far by going through u
وال أل U
عن طريق ال V يعني بنقارن ونشوف هل هيكون افضل لو وصلنا لل -
: اللي هو d(v) وده بيتحدد عن طريق
d[v] the value of the shortest path from s, initialized to 0 at the start .
Lec 10 Algorithms
RELAXATION
Lec 10 Algorithms
DIJKSTRA'S ALGORITHM
Non-negative edge weights
- Greedy, similar to Prim's algorithm for
MST.
- Like breadth-first search (if all weights
= 1, one can simply use BFS).
- Use Q, a priority queue which is re-
organized whenever some d
decreases.
Maintains a set S of vertices
At each step select "closest" vertex u,
add it to S, and relax all edges from u
See:
Lec 10 Algorithms
EXAMPLE:
Lec 10 Algorithms
DIJKSTRA’S RUNNING TIME
- Extract-Min executed |V| time
- Decrease-Key executed |E| time
- Time = |V| T Extract-Min + |E| T Decrease-Key
T depends on different Q implementations
Lec 10 Algorithms
SHORTEST PATHS IN DAG
(DIRECTED ACYCLIC GRAPH)
Topologically sort vertices in
G;
Initialize(G, s);
for each u in V[G] (in order) do
for each v in Adj[u] do
Relax(u, v, w)
End for
End for
Topologically الن الرؤس كلها مترتبةExtract-min حذفنا خطوة
Lec 10 Algorithms
EXAMPLE:
Lec 10 Algorithms
BELLMAN-FORD ALGORITHM
Time Complexity is
(|V|-1)|E| + |E| = O(VE).
Lec 10 Algorithms
Lec 10 Algorithms
Difference between Dijkstra’s and Bellman-Ford algorithms:
Dijkstra’s algorithm Bellman-Ford algorithm
doesn’t work when there are negative detects negative cycles (returns false) or
edges returns the shortest path-tree
Lec 10 Algorithms
14
Algorithms