SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Downloaden Sie, um offline zu lesen
Shortest Paths
in a Graph
Fundamental Algorithms
The Problems
● Given a directed graph G with edge weights,
find
■ The shortest path from a given vertex s to all other
vertices (Single Source Shortest Paths)
■ The shortest paths between all pairs of vertices (All
Pairs Shortest Paths)
● where the length of a path is the sum of its
edge weights.
Shortest Paths: Applications
Shortest Paths: Algorithms
● Single-Source Shortest Paths (SSSP)
■ Dijkstra’s
■ Bellman-Ford
● All-Pairs Shortest Paths (APSP)
■ Floyd-Warshall
A Fact About Shortest Paths
● Theorem: If p is a shortest path from u to v,
then any subpath of p is also a shortest path.
● Proof: Consider a subpath of p from x to y. If
there were a shorter path from x to y, then
there would be a shorter path from u to v.
u x y v
shorter?
Single-Source Shortest Paths
● Given a directed graph with weighted
edges, what are the shortest paths from
some source vertex s to all other vertices?
● Note: shortest path to single destination
cannot be done asymptotically faster, as far
as we know.
3
11
9
5
0
3
6
5
4
3
6
2
1 2 7s
Path Recovery
● We would like to find the path itself, not just
its length.
● We’ll construct a shortest-paths tree:
3
11
9
5
0
3
6
5
4
3
6
2 7
2
1
s
u v
x y
3
11
9
5
0
3
6
5
3
6
2 7
42
1
s
u v
x y
Shortest-Paths Idea
● d(u,v)  length of the shortest path from u to v.
● All SSSP algorithms maintain a field d[u] for every vertex
u. d[u] will be an estimate of d(s,u). As the algorithm
progresses, we will refine d[u] until, at termination,
d[u] = d(s,u). Whenever we discover a new shortest path to
u, we update d[u].
● In fact, d[u] will always be an overestimate of d(s,u):
● d[u] d(s,u)
● We’ll use p[u] to point to the parent (or predecessor) of u on
the shortest path from s to u. We update p[u] when we
update d[u].
SSSP Subroutine
RELAX(u, v, w)
> (Maybe) improve our estimate of the distance to v
> by considering a path along the edge (u, v).
if d[u] + w(u, v) < d[v] then
d[v]  d[u] + w(u, v) > actually, DECREASE-KEY
p[v]  u > remember predecessor on path
u v
w(u,v)
d[v]d[u]
Dijkstra’s Algorithm
● Assume that all edge weights are  0.
● Idea: say we have a set K containing all
vertices whose shortest paths from s are
known
(i.e. d[u] = d(s,u) for all u in K).
● Now look at the “frontier” of K—all vertices
adjacent to a vertex in K. the rest
of the
graph
s
K
Dijkstra’s: Theorem
● At each frontier
vertex u, update d[u]
to be the minimum
from all edges from
K.
● Now pick the frontier
vertex u with the
smallest value of
d[u].
● Claim: d[u] = d(s,u)
s
4
9
6
6
2
1
3
8
min(4+2, 6+1) = 6
min(4+8, 6+3) = 9
Dijkstra’s Algorithm - Example
10
1
5
2
64
9
7
2 3
Dijkstra’s Algorithm - Example
0




10
1
5
2
64
9
7
2 3
Dijkstra’s Algorithm - Example
0
5
10


10
1
5
2
64
9
7
2 3
Dijkstra’s Algorithm - Example
0
5
10


10
1
5
2
64
9
7
2 3
Dijkstra’s Algorithm - Example
0
5
8
7
14
10
1
5
2
64
9
7
2 3
Dijkstra’s Algorithm - Example
0
5
8
7
14
10
1
5
2
64
9
7
2 3
Dijkstra’s Algorithm - Example
0
5
8
7
13
10
1
5
2
64
9
7
2 3
Dijkstra’s Algorithm - Example
0
5
8
7
13
10
1
5
2
64
9
7
2 3
Dijkstra’s Algorithm - Example
0
5
8
7
9
10
1
5
2
64
9
7
2 3
Dijkstra’s Algorithm - Example
0
5
8
7
9
10
1
5
2
64
9
7
2 3
Code for Dijkstra’s Algorithm
1 DIJKSTRA(G, w, s) > Graph, weights, start vertex
2 for each vertex v in V[G] do
3 d[v]  
4 p[v]  NIL
5 d[s]  0
6 Q  BUILD-PRIORITY-QUEUE(V[G])
7 > Q is V[G] - K
8 while Q is not empty do
9 u = EXTRACT-MIN(Q)
10 for each vertex v in Adj[u]
11 RELAX(u, v, w) // DECREASE_KEY
Running Time of Dijkstra
● Initialization: q(V)
● Building priority queue: q(V)
● “while” loop done |V| times
● |V| calls of EXTRACT-MIN
● Inner “edge” loop done |E| times
● At most |E| calls of DECREASE-KEY
● Total time:
● (V + V  TEXTRACT-MIN + E  TDECREASE-KEY
Dijkstra Running Time (cont.)
● 1. Priority queue is an array.
EXTRACT-MIN in (n) time, DECREASE-KEY in (1)
Total time: (V + VV + E) = (V2)
● 2. (“Modified Dijkstra”)
Priority queue is a binary (standard) heap.
EXTRACT-MIN in (lgn) time, also DECREASE-KEY
Total time: (VlgV + ElgV)
● 3. Priority queue is Fibonacci heap. (Of theoretical interest
only.)
EXTRACT-MIN in (lgn),
DECREASE-KEY in (1) (amortized)
Total time: (VlgV+E)
The Bellman-Ford Algorithm
● Handles negative edge weights
● Detects negative cycles
● Is slower than Dijkstra
4
5
-10
a negative cycle
Bellman-Ford: Idea
● Repeatedly update d for all pairs of vertices
connected by an edge.
● Theorem: If u and v are two vertices with an
edge from u to v, and s  u  v is a shortest
path, and d[u] = d(s,u),
● then d[u]+w(u,v) is the length of a shortest
path to v.
● Proof: Since s u  v is a shortest path, its
length is d(s,u) + w(u,v) = d[u] + w(u,v). 
Why Bellman-Ford Works
• On the first pass, we find d(s,u) for all vertices whose
shortest paths have one edge.
• On the second pass, the d[u] values computed for the one-
edge-away vertices are correct (= d(s,u)), so they are used
to compute the correct d values for vertices whose shortest
paths have two edges.
• Since no shortest path can have more than |V[G]|-1 edges,
after that many passes all d values are correct.
• Note: all vertices not reachable from s will have their
original values of infinity. (Same, by the way, for
Dijkstra).
Bellman-Ford: Algorithm
● BELLMAN-FORD(G, w, s)
● 1 foreach vertex v V[G] do //INIT_SINGLE_SOURCE
● 2 d[v] 
● 3 p[v] NIL
● 4 d[s] 0
● 5 for i  1 to |V[G]|-1 do > each iteration is a “pass”
● 6 for each edge (u,v) in E[G] do
● 7 RELAX(u, v, w)
● 8 > check for negative cycles
● 9 for each edge (u,v) in E[G] do
● 10 if d[v] > d[u] + w(u,v) then
● 11 return FALSE
● 12 return TRUE
Running time:(VE)
Negative Cycle Detection
● What if there is a negative-weight
cycle reachable from s?
● Assume: d[u]  d[x]+4
● d[v]  d[u]+5
● d[x]  d[v]-10
● Adding:
● d[u]+d[v]+d[x]  d[x]+d[u]+d[v]-1
● Because it’s a cycle, vertices on left are same as those on right.
Thus we get 0  -1; a contradiction.
So for at least one edge (u,v),
● d[v] > d[u] + w(u,v)
● This is exactly what Bellman-Ford checks for.
u
x
v
4
5
-10
Bellman-Ford Algorithm - Example
6
7
7
-3
2
8
-4
9
5
-2
Bellman-Ford Algorithm - Example
0




6
7
7
-3
2
8
-4
9
5
-2
Bellman-Ford Algorithm - Example
0
7
6


6
7
7
-3
2
8
-4
9
5
-2
Bellman-Ford Algorithm - Example
0
7
6
2
4
6
7
7
-3
2
8
-4
9
5
-2
Bellman-Ford Algorithm - Example
0
7
2
2
4
6
5
7
7
-3
2
8
-2
-4
9
Bellman-Ford Algorithm - Example
0
7
2
-2
4
6
5
7
7
-3
2
8
-2
-4
9
All-Pairs Shortest Paths
Given graph (directed or undirected) G = (V,E) with
weight function w: E  R find for all pairs of vertices
u,v  V the minimum possible weight for path from u to v.
Now, let be the minimum weight of any path from vertex i to
vertex j that contains at most m edges.
For m>=1
Floyd-Warshall Algorithm - Idea
Floyd-Warshall Algorithm - Idea
Floyd-Warshall Algorithm - Idea
ds,t
(i) – the shortest path from s to t containing only vertices
v1, ..., vi
ds,t
(0) = w(s,t)
ds,t
(k) =
w(s,t) if k = 0
min{ds,t
(k-1), ds,k
(k-1) + dk,t
(k-1)} if k > 0
Floyd-Warshall Algorithm -
Algorithm
FloydWarshall(matrix W, integer n)
for k  1 to n do
for i  1 to n do
for j  1 to n do
dij
(k)  min(dij
(k-1), dik
(k-1) + dkj
(k-1))
return D(n)
Floyd-Warshall Algorithm -
Example
2
45
1 3
3 4
-4
-5
6
7 1
8
2
0 3 8  -4
 0  1 7
 4 0  
2  -5 0 
   6 0
W
Floyd-Warshall Algorithm -
Example
0 3 8  -4
 0  1 7
 4 0  
2  -5 0 
   6 0
0 0 0 0
0 0 0
0 0
0 0 0
0 0
D(0) (0)
Floyd-Warshall Algorithm -
Example
0 3 8  -4
 0  1 7
 4 0  
2 5 -5 0 -2
   6 0
0 0 0 0
0 0 0
0 0
0 1 0 0 1
0 0
D(1) (1)
Floyd-Warshall Algorithm -
Example
0 3 8 4 -4
 0  1 7
 4 0 5 11
2 5 -5 0 -2
   6 0
0 0 0 2 0
0 0 0
0 0 2 2
0 1 0 0 1
0 0
D(2) (2)
Floyd-Warshall Algorithm -
Example
0 3 8 4 -4
 0  1 7
 4 0 5 11
2 -1 -5 0 -2
   6 0
0 0 0 2 0
0 0 0
0 0 2 2
0 3 0 0 1
0 0
D(3) (3)
Floyd-Warshall Algorithm -
Example
0 3 -1 4 -4
3 0 -4 1 -1
7 4 0 5 3
2 -1 -5 0 -2
8 5 1 6 0
0 0 4 2 0
4 0 4 0 1
4 0 0 2 1
0 3 0 0 1
4 3 4 0 0
D(4) (4)
Floyd-Warshall Algorithm -
Example
0 3 -1 2 -4
3 0 -4 1 -1
7 4 0 5 3
2 -1 -5 0 -2
8 5 1 6 0
0 0 4 5 0
4 0 4 0 1
4 0 0 2 1
0 3 0 0 1
4 3 4 0 0
D(5) (5)

Weitere ähnliche Inhalte

Was ist angesagt?

Dijkstra's Algorithm
Dijkstra's AlgorithmDijkstra's Algorithm
Dijkstra's AlgorithmTamzida_Azad
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithmmeisamstar
 
Dijkstra's algorithm presentation
Dijkstra's algorithm presentationDijkstra's algorithm presentation
Dijkstra's algorithm presentationSubid Biswas
 
Bellman Ford's Algorithm
Bellman Ford's AlgorithmBellman Ford's Algorithm
Bellman Ford's AlgorithmTanmay Baranwal
 
Dijkstra’S Algorithm
Dijkstra’S AlgorithmDijkstra’S Algorithm
Dijkstra’S Algorithmami_01
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithmsRajendran
 
Dijkstra algorithm a dynammic programming approach
Dijkstra algorithm   a dynammic programming approachDijkstra algorithm   a dynammic programming approach
Dijkstra algorithm a dynammic programming approachAkash Sethiya
 
Bellmanford . montaser hamza.iraq
Bellmanford . montaser hamza.iraqBellmanford . montaser hamza.iraq
Bellmanford . montaser hamza.iraqmontaser185
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithmSrikrishnan Suresh
 
Bellman Ford Routing Algorithm-Computer Networks
Bellman Ford Routing Algorithm-Computer NetworksBellman Ford Routing Algorithm-Computer Networks
Bellman Ford Routing Algorithm-Computer NetworksSimranJain63
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treeoneous
 

Was ist angesagt? (20)

Dijkstra
DijkstraDijkstra
Dijkstra
 
Dijkstra's Algorithm
Dijkstra's AlgorithmDijkstra's Algorithm
Dijkstra's Algorithm
 
Dijkstra's Algorithm
Dijkstra's Algorithm Dijkstra's Algorithm
Dijkstra's Algorithm
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithm
 
Dijkstra's algorithm presentation
Dijkstra's algorithm presentationDijkstra's algorithm presentation
Dijkstra's algorithm presentation
 
Bellman Ford's Algorithm
Bellman Ford's AlgorithmBellman Ford's Algorithm
Bellman Ford's Algorithm
 
Dijkstra’S Algorithm
Dijkstra’S AlgorithmDijkstra’S Algorithm
Dijkstra’S Algorithm
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Prim's algorithm
Prim's algorithmPrim's algorithm
Prim's algorithm
 
Dijkstra algorithm a dynammic programming approach
Dijkstra algorithm   a dynammic programming approachDijkstra algorithm   a dynammic programming approach
Dijkstra algorithm a dynammic programming approach
 
Graph algorithm
Graph algorithmGraph algorithm
Graph algorithm
 
Floyd Warshall Algorithm
Floyd Warshall AlgorithmFloyd Warshall Algorithm
Floyd Warshall Algorithm
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
 
Bellmanford . montaser hamza.iraq
Bellmanford . montaser hamza.iraqBellmanford . montaser hamza.iraq
Bellmanford . montaser hamza.iraq
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithm
 
Bellman Ford Routing Algorithm-Computer Networks
Bellman Ford Routing Algorithm-Computer NetworksBellman Ford Routing Algorithm-Computer Networks
Bellman Ford Routing Algorithm-Computer Networks
 
Tsp branch and-bound
Tsp branch and-boundTsp branch and-bound
Tsp branch and-bound
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning tree
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 

Andere mochten auch

Shortest path problem
Shortest path problemShortest path problem
Shortest path problemIfra Ilyas
 
Dijkstra's algorithm
Dijkstra's algorithmDijkstra's algorithm
Dijkstra's algorithmgsp1294
 
Discrete Mathematics Presentation
Discrete Mathematics PresentationDiscrete Mathematics Presentation
Discrete Mathematics PresentationSalman Elahi
 
Bellman ford Algorithm
Bellman ford AlgorithmBellman ford Algorithm
Bellman ford Algorithmtaimurkhan803
 
Shortest Path Problem: Algoritma Dijkstra
Shortest Path Problem: Algoritma DijkstraShortest Path Problem: Algoritma Dijkstra
Shortest Path Problem: Algoritma DijkstraOnggo Wiryawan
 
Shortest Path Search in Real Road Networks with pgRouting
Shortest Path Search in Real Road Networks with pgRoutingShortest Path Search in Real Road Networks with pgRouting
Shortest Path Search in Real Road Networks with pgRoutingDaniel Kastl
 
Shortest path search for real road networks and dynamic costs with pgRouting
Shortest path search for real road networks and dynamic costs with pgRoutingShortest path search for real road networks and dynamic costs with pgRouting
Shortest path search for real road networks and dynamic costs with pgRoutingantonpa
 
Connected components and shortest path
Connected components and shortest pathConnected components and shortest path
Connected components and shortest pathKaushik Koneru
 
B trees and_b__trees
B trees and_b__treesB trees and_b__trees
B trees and_b__treesmeghu123
 
Conservation of codon optimality
Conservation of codon optimalityConservation of codon optimality
Conservation of codon optimalityAlistair Martin
 
Solving The Shortest Path Tour Problem
Solving The Shortest Path Tour ProblemSolving The Shortest Path Tour Problem
Solving The Shortest Path Tour ProblemNozir Shokirov
 
Bellman ford (part-ii)
Bellman ford (part-ii)Bellman ford (part-ii)
Bellman ford (part-ii)Zain Zahid
 
Bellman ford (part-i)
Bellman ford (part-i)Bellman ford (part-i)
Bellman ford (part-i)Zain Zahid
 
Floyd Warshall algorithm easy way to compute - Malinga
Floyd Warshall algorithm easy way to compute - MalingaFloyd Warshall algorithm easy way to compute - Malinga
Floyd Warshall algorithm easy way to compute - MalingaMalinga Perera
 
Dijkstra & flooding ppt(Routing algorithm)
Dijkstra & flooding ppt(Routing algorithm)Dijkstra & flooding ppt(Routing algorithm)
Dijkstra & flooding ppt(Routing algorithm)Anshul gour
 

Andere mochten auch (20)

Shortest path problem
Shortest path problemShortest path problem
Shortest path problem
 
Shortest path algorithm
Shortest  path algorithmShortest  path algorithm
Shortest path algorithm
 
Dijkstra's algorithm
Dijkstra's algorithmDijkstra's algorithm
Dijkstra's algorithm
 
Discrete Mathematics Presentation
Discrete Mathematics PresentationDiscrete Mathematics Presentation
Discrete Mathematics Presentation
 
Bellman ford Algorithm
Bellman ford AlgorithmBellman ford Algorithm
Bellman ford Algorithm
 
Shortest Path Problem: Algoritma Dijkstra
Shortest Path Problem: Algoritma DijkstraShortest Path Problem: Algoritma Dijkstra
Shortest Path Problem: Algoritma Dijkstra
 
Shortest Path Search in Real Road Networks with pgRouting
Shortest Path Search in Real Road Networks with pgRoutingShortest Path Search in Real Road Networks with pgRouting
Shortest Path Search in Real Road Networks with pgRouting
 
2.5 graph dfs
2.5 graph dfs2.5 graph dfs
2.5 graph dfs
 
Shortest path search for real road networks and dynamic costs with pgRouting
Shortest path search for real road networks and dynamic costs with pgRoutingShortest path search for real road networks and dynamic costs with pgRouting
Shortest path search for real road networks and dynamic costs with pgRouting
 
Connected components and shortest path
Connected components and shortest pathConnected components and shortest path
Connected components and shortest path
 
B trees and_b__trees
B trees and_b__treesB trees and_b__trees
B trees and_b__trees
 
Conservation of codon optimality
Conservation of codon optimalityConservation of codon optimality
Conservation of codon optimality
 
Avl trees
Avl treesAvl trees
Avl trees
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Solving The Shortest Path Tour Problem
Solving The Shortest Path Tour ProblemSolving The Shortest Path Tour Problem
Solving The Shortest Path Tour Problem
 
Bellman ford (part-ii)
Bellman ford (part-ii)Bellman ford (part-ii)
Bellman ford (part-ii)
 
Bellman ford (part-i)
Bellman ford (part-i)Bellman ford (part-i)
Bellman ford (part-i)
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Floyd Warshall algorithm easy way to compute - Malinga
Floyd Warshall algorithm easy way to compute - MalingaFloyd Warshall algorithm easy way to compute - Malinga
Floyd Warshall algorithm easy way to compute - Malinga
 
Dijkstra & flooding ppt(Routing algorithm)
Dijkstra & flooding ppt(Routing algorithm)Dijkstra & flooding ppt(Routing algorithm)
Dijkstra & flooding ppt(Routing algorithm)
 

Ähnlich wie Shortest Path in Graph

Single sourceshortestpath by emad
Single sourceshortestpath by emadSingle sourceshortestpath by emad
Single sourceshortestpath by emadKazi Emad
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithmRuchika Sinha
 
2.6 all pairsshortestpath
2.6 all pairsshortestpath2.6 all pairsshortestpath
2.6 all pairsshortestpathKrish_ver2
 
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdfDKTaxation
 
lecture 21
lecture 21lecture 21
lecture 21sajinsc
 
Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10Traian Rebedea
 
Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Naor Ami
 
Randomized algorithms all pairs shortest path
Randomized algorithms  all pairs shortest pathRandomized algorithms  all pairs shortest path
Randomized algorithms all pairs shortest pathMohammad Akbarizadeh
 
bellman-ford Theorem.ppt
bellman-ford Theorem.pptbellman-ford Theorem.ppt
bellman-ford Theorem.pptSaimaShaheen14
 
Graphs: Finding shortest paths
Graphs: Finding shortest pathsGraphs: Finding shortest paths
Graphs: Finding shortest pathsFulvio Corno
 
04 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x204 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x2MuradAmn
 

Ähnlich wie Shortest Path in Graph (20)

Shortest path
Shortest pathShortest path
Shortest path
 
Graph 3
Graph 3Graph 3
Graph 3
 
Single sourceshortestpath by emad
Single sourceshortestpath by emadSingle sourceshortestpath by emad
Single sourceshortestpath by emad
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 
dijkstraC.ppt
dijkstraC.pptdijkstraC.ppt
dijkstraC.ppt
 
2.6 all pairsshortestpath
2.6 all pairsshortestpath2.6 all pairsshortestpath
2.6 all pairsshortestpath
 
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
 
lecture 21
lecture 21lecture 21
lecture 21
 
Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10
 
Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14
 
Randomized algorithms all pairs shortest path
Randomized algorithms  all pairs shortest pathRandomized algorithms  all pairs shortest path
Randomized algorithms all pairs shortest path
 
bellman-ford Theorem.ppt
bellman-ford Theorem.pptbellman-ford Theorem.ppt
bellman-ford Theorem.ppt
 
4900514.ppt
4900514.ppt4900514.ppt
4900514.ppt
 
Graphs: Finding shortest paths
Graphs: Finding shortest pathsGraphs: Finding shortest paths
Graphs: Finding shortest paths
 
Dijkstra c
Dijkstra cDijkstra c
Dijkstra c
 
Chapter 25 aoa
Chapter 25 aoaChapter 25 aoa
Chapter 25 aoa
 
04 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x204 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x2
 
04 greedyalgorithmsii
04 greedyalgorithmsii04 greedyalgorithmsii
04 greedyalgorithmsii
 
Topological Sort
Topological SortTopological Sort
Topological Sort
 
Ppt 1
Ppt 1Ppt 1
Ppt 1
 

Mehr von Dr Sandeep Kumar Poonia

An improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithmAn improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithmDr Sandeep Kumar Poonia
 
Modified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithmModified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithmDr Sandeep Kumar Poonia
 
Enhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithmEnhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithmDr Sandeep Kumar Poonia
 
Memetic search in differential evolution algorithm
Memetic search in differential evolution algorithmMemetic search in differential evolution algorithm
Memetic search in differential evolution algorithmDr Sandeep Kumar Poonia
 
Improved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithmImproved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithmDr Sandeep Kumar Poonia
 
Comparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithmComparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithmDr Sandeep Kumar Poonia
 
A novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithmA novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithmDr Sandeep Kumar Poonia
 
Multiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked listsMultiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked listsDr Sandeep Kumar Poonia
 
Sunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithmSunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithmDr Sandeep Kumar Poonia
 
New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm Dr Sandeep Kumar Poonia
 
Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...Dr Sandeep Kumar Poonia
 
Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...Dr Sandeep Kumar Poonia
 

Mehr von Dr Sandeep Kumar Poonia (20)

Soft computing
Soft computingSoft computing
Soft computing
 
An improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithmAn improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithm
 
Modified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithmModified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithm
 
Enhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithmEnhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithm
 
RMABC
RMABCRMABC
RMABC
 
Memetic search in differential evolution algorithm
Memetic search in differential evolution algorithmMemetic search in differential evolution algorithm
Memetic search in differential evolution algorithm
 
Improved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithmImproved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithm
 
Comparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithmComparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithm
 
A novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithmA novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithm
 
Multiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked listsMultiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked lists
 
Sunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithmSunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithm
 
New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm
 
A new approach of program slicing
A new approach of program slicingA new approach of program slicing
A new approach of program slicing
 
Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...
 
Enhanced abc algo for tsp
Enhanced abc algo for tspEnhanced abc algo for tsp
Enhanced abc algo for tsp
 
Database aggregation using metadata
Database aggregation using metadataDatabase aggregation using metadata
Database aggregation using metadata
 
Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...
 
Lecture28 tsp
Lecture28 tspLecture28 tsp
Lecture28 tsp
 
Lecture27 linear programming
Lecture27 linear programmingLecture27 linear programming
Lecture27 linear programming
 
Lecture26
Lecture26Lecture26
Lecture26
 

Kürzlich hochgeladen

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Kürzlich hochgeladen (20)

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Shortest Path in Graph

  • 1. Shortest Paths in a Graph Fundamental Algorithms
  • 2. The Problems ● Given a directed graph G with edge weights, find ■ The shortest path from a given vertex s to all other vertices (Single Source Shortest Paths) ■ The shortest paths between all pairs of vertices (All Pairs Shortest Paths) ● where the length of a path is the sum of its edge weights.
  • 4. Shortest Paths: Algorithms ● Single-Source Shortest Paths (SSSP) ■ Dijkstra’s ■ Bellman-Ford ● All-Pairs Shortest Paths (APSP) ■ Floyd-Warshall
  • 5. A Fact About Shortest Paths ● Theorem: If p is a shortest path from u to v, then any subpath of p is also a shortest path. ● Proof: Consider a subpath of p from x to y. If there were a shorter path from x to y, then there would be a shorter path from u to v. u x y v shorter?
  • 6. Single-Source Shortest Paths ● Given a directed graph with weighted edges, what are the shortest paths from some source vertex s to all other vertices? ● Note: shortest path to single destination cannot be done asymptotically faster, as far as we know. 3 11 9 5 0 3 6 5 4 3 6 2 1 2 7s
  • 7. Path Recovery ● We would like to find the path itself, not just its length. ● We’ll construct a shortest-paths tree: 3 11 9 5 0 3 6 5 4 3 6 2 7 2 1 s u v x y 3 11 9 5 0 3 6 5 3 6 2 7 42 1 s u v x y
  • 8. Shortest-Paths Idea ● d(u,v)  length of the shortest path from u to v. ● All SSSP algorithms maintain a field d[u] for every vertex u. d[u] will be an estimate of d(s,u). As the algorithm progresses, we will refine d[u] until, at termination, d[u] = d(s,u). Whenever we discover a new shortest path to u, we update d[u]. ● In fact, d[u] will always be an overestimate of d(s,u): ● d[u] d(s,u) ● We’ll use p[u] to point to the parent (or predecessor) of u on the shortest path from s to u. We update p[u] when we update d[u].
  • 9. SSSP Subroutine RELAX(u, v, w) > (Maybe) improve our estimate of the distance to v > by considering a path along the edge (u, v). if d[u] + w(u, v) < d[v] then d[v]  d[u] + w(u, v) > actually, DECREASE-KEY p[v]  u > remember predecessor on path u v w(u,v) d[v]d[u]
  • 10. Dijkstra’s Algorithm ● Assume that all edge weights are  0. ● Idea: say we have a set K containing all vertices whose shortest paths from s are known (i.e. d[u] = d(s,u) for all u in K). ● Now look at the “frontier” of K—all vertices adjacent to a vertex in K. the rest of the graph s K
  • 11. Dijkstra’s: Theorem ● At each frontier vertex u, update d[u] to be the minimum from all edges from K. ● Now pick the frontier vertex u with the smallest value of d[u]. ● Claim: d[u] = d(s,u) s 4 9 6 6 2 1 3 8 min(4+2, 6+1) = 6 min(4+8, 6+3) = 9
  • 12. Dijkstra’s Algorithm - Example 10 1 5 2 64 9 7 2 3
  • 13. Dijkstra’s Algorithm - Example 0     10 1 5 2 64 9 7 2 3
  • 14. Dijkstra’s Algorithm - Example 0 5 10   10 1 5 2 64 9 7 2 3
  • 15. Dijkstra’s Algorithm - Example 0 5 10   10 1 5 2 64 9 7 2 3
  • 16. Dijkstra’s Algorithm - Example 0 5 8 7 14 10 1 5 2 64 9 7 2 3
  • 17. Dijkstra’s Algorithm - Example 0 5 8 7 14 10 1 5 2 64 9 7 2 3
  • 18. Dijkstra’s Algorithm - Example 0 5 8 7 13 10 1 5 2 64 9 7 2 3
  • 19. Dijkstra’s Algorithm - Example 0 5 8 7 13 10 1 5 2 64 9 7 2 3
  • 20. Dijkstra’s Algorithm - Example 0 5 8 7 9 10 1 5 2 64 9 7 2 3
  • 21. Dijkstra’s Algorithm - Example 0 5 8 7 9 10 1 5 2 64 9 7 2 3
  • 22. Code for Dijkstra’s Algorithm 1 DIJKSTRA(G, w, s) > Graph, weights, start vertex 2 for each vertex v in V[G] do 3 d[v]   4 p[v]  NIL 5 d[s]  0 6 Q  BUILD-PRIORITY-QUEUE(V[G]) 7 > Q is V[G] - K 8 while Q is not empty do 9 u = EXTRACT-MIN(Q) 10 for each vertex v in Adj[u] 11 RELAX(u, v, w) // DECREASE_KEY
  • 23. Running Time of Dijkstra ● Initialization: q(V) ● Building priority queue: q(V) ● “while” loop done |V| times ● |V| calls of EXTRACT-MIN ● Inner “edge” loop done |E| times ● At most |E| calls of DECREASE-KEY ● Total time: ● (V + V  TEXTRACT-MIN + E  TDECREASE-KEY
  • 24. Dijkstra Running Time (cont.) ● 1. Priority queue is an array. EXTRACT-MIN in (n) time, DECREASE-KEY in (1) Total time: (V + VV + E) = (V2) ● 2. (“Modified Dijkstra”) Priority queue is a binary (standard) heap. EXTRACT-MIN in (lgn) time, also DECREASE-KEY Total time: (VlgV + ElgV) ● 3. Priority queue is Fibonacci heap. (Of theoretical interest only.) EXTRACT-MIN in (lgn), DECREASE-KEY in (1) (amortized) Total time: (VlgV+E)
  • 25. The Bellman-Ford Algorithm ● Handles negative edge weights ● Detects negative cycles ● Is slower than Dijkstra 4 5 -10 a negative cycle
  • 26. Bellman-Ford: Idea ● Repeatedly update d for all pairs of vertices connected by an edge. ● Theorem: If u and v are two vertices with an edge from u to v, and s  u  v is a shortest path, and d[u] = d(s,u), ● then d[u]+w(u,v) is the length of a shortest path to v. ● Proof: Since s u  v is a shortest path, its length is d(s,u) + w(u,v) = d[u] + w(u,v). 
  • 27. Why Bellman-Ford Works • On the first pass, we find d(s,u) for all vertices whose shortest paths have one edge. • On the second pass, the d[u] values computed for the one- edge-away vertices are correct (= d(s,u)), so they are used to compute the correct d values for vertices whose shortest paths have two edges. • Since no shortest path can have more than |V[G]|-1 edges, after that many passes all d values are correct. • Note: all vertices not reachable from s will have their original values of infinity. (Same, by the way, for Dijkstra).
  • 28. Bellman-Ford: Algorithm ● BELLMAN-FORD(G, w, s) ● 1 foreach vertex v V[G] do //INIT_SINGLE_SOURCE ● 2 d[v]  ● 3 p[v] NIL ● 4 d[s] 0 ● 5 for i  1 to |V[G]|-1 do > each iteration is a “pass” ● 6 for each edge (u,v) in E[G] do ● 7 RELAX(u, v, w) ● 8 > check for negative cycles ● 9 for each edge (u,v) in E[G] do ● 10 if d[v] > d[u] + w(u,v) then ● 11 return FALSE ● 12 return TRUE Running time:(VE)
  • 29. Negative Cycle Detection ● What if there is a negative-weight cycle reachable from s? ● Assume: d[u]  d[x]+4 ● d[v]  d[u]+5 ● d[x]  d[v]-10 ● Adding: ● d[u]+d[v]+d[x]  d[x]+d[u]+d[v]-1 ● Because it’s a cycle, vertices on left are same as those on right. Thus we get 0  -1; a contradiction. So for at least one edge (u,v), ● d[v] > d[u] + w(u,v) ● This is exactly what Bellman-Ford checks for. u x v 4 5 -10
  • 30. Bellman-Ford Algorithm - Example 6 7 7 -3 2 8 -4 9 5 -2
  • 31. Bellman-Ford Algorithm - Example 0     6 7 7 -3 2 8 -4 9 5 -2
  • 32. Bellman-Ford Algorithm - Example 0 7 6   6 7 7 -3 2 8 -4 9 5 -2
  • 33. Bellman-Ford Algorithm - Example 0 7 6 2 4 6 7 7 -3 2 8 -4 9 5 -2
  • 34. Bellman-Ford Algorithm - Example 0 7 2 2 4 6 5 7 7 -3 2 8 -2 -4 9
  • 35. Bellman-Ford Algorithm - Example 0 7 2 -2 4 6 5 7 7 -3 2 8 -2 -4 9
  • 36. All-Pairs Shortest Paths Given graph (directed or undirected) G = (V,E) with weight function w: E  R find for all pairs of vertices u,v  V the minimum possible weight for path from u to v.
  • 37. Now, let be the minimum weight of any path from vertex i to vertex j that contains at most m edges. For m>=1
  • 38.
  • 39.
  • 42. Floyd-Warshall Algorithm - Idea ds,t (i) – the shortest path from s to t containing only vertices v1, ..., vi ds,t (0) = w(s,t) ds,t (k) = w(s,t) if k = 0 min{ds,t (k-1), ds,k (k-1) + dk,t (k-1)} if k > 0
  • 43. Floyd-Warshall Algorithm - Algorithm FloydWarshall(matrix W, integer n) for k  1 to n do for i  1 to n do for j  1 to n do dij (k)  min(dij (k-1), dik (k-1) + dkj (k-1)) return D(n)
  • 44. Floyd-Warshall Algorithm - Example 2 45 1 3 3 4 -4 -5 6 7 1 8 2 0 3 8  -4  0  1 7  4 0   2  -5 0     6 0 W
  • 45. Floyd-Warshall Algorithm - Example 0 3 8  -4  0  1 7  4 0   2  -5 0     6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 D(0) (0)
  • 46. Floyd-Warshall Algorithm - Example 0 3 8  -4  0  1 7  4 0   2 5 -5 0 -2    6 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 D(1) (1)
  • 47. Floyd-Warshall Algorithm - Example 0 3 8 4 -4  0  1 7  4 0 5 11 2 5 -5 0 -2    6 0 0 0 0 2 0 0 0 0 0 0 2 2 0 1 0 0 1 0 0 D(2) (2)
  • 48. Floyd-Warshall Algorithm - Example 0 3 8 4 -4  0  1 7  4 0 5 11 2 -1 -5 0 -2    6 0 0 0 0 2 0 0 0 0 0 0 2 2 0 3 0 0 1 0 0 D(3) (3)
  • 49. Floyd-Warshall Algorithm - Example 0 3 -1 4 -4 3 0 -4 1 -1 7 4 0 5 3 2 -1 -5 0 -2 8 5 1 6 0 0 0 4 2 0 4 0 4 0 1 4 0 0 2 1 0 3 0 0 1 4 3 4 0 0 D(4) (4)
  • 50. Floyd-Warshall Algorithm - Example 0 3 -1 2 -4 3 0 -4 1 -1 7 4 0 5 3 2 -1 -5 0 -2 8 5 1 6 0 0 0 4 5 0 4 0 4 0 1 4 0 0 2 1 0 3 0 0 1 4 3 4 0 0 D(5) (5)