SlideShare a Scribd company logo
AAD CSE SRMAP 1
Shortest Paths
C
B
A
E
D
F
0
3
2
8
5 8
4
8
7 1
2 5
2
3 9
AAD CSE SRMAP 2
Weighted Graphs
In a weighted graph, each edge has an associated numerical
value, called the weight of the edge
Edge weights may represent, distances, costs, etc.
Example:
 In a flight route graph, the weight of an edge represents the
distance in miles between the endpoint airports
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
AAD CSE SRMAP 3
Shortest Path Problem
Given a weighted graph and two vertices u and v, we want to
find a path of minimum total weight between u and v.
 Length of a path is the sum of the weights of its edges.
Example:
 Shortest path between Providence and Honolulu
Applications
 Internet packet routing
 Flight reservations
 Driving directions
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
AAD CSE SRMAP 4
Shortest Path Properties
Property 1:
A subpath of a shortest path is itself a shortest path
Property 2:
There is a tree of shortest paths from a start vertex to all the other
vertices
Example:
Tree of shortest paths from Providence
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
Dijkstra’s Algorithm
U  Designated node
Set1  Remaining nodes
Repeat
{
In the mapping between U and Set1 find V which
is the minimum weight(distance) vertex from U.
Remove V from Set1.
Improve the weights(distances) from U to all
other nodes through V
}
Until set1 is empty
AAD CSE SRMAP 5
AAD CSE SRMAP 6
AAD CSE SRMAP 7
Dijkstra’s Algorithm
The distance of a vertex
v from a vertex s is the
length of a shortest path
between s and v
Dijkstra’s algorithm
computes the distances
of all the vertices from a
given start vertex s
Assumptions:
 the graph is connected
 the edges are
undirected
 the edge weights are
nonnegative
We grow a “cloud” of vertices,
beginning with s and eventually
covering all the vertices
We store with each vertex v a
label d(v) representing the
distance of v from s in the
subgraph consisting of the cloud
and its adjacent vertices
At each step
 We add to the cloud the vertex
u outside the cloud with the
smallest distance label, d(u)
 We update the labels of the
vertices adjacent to u
AAD CSE SRMAP 8
Edge Relaxation
Consider an edge e = (u,z)
such that
 u is the vertex most recently
added to the cloud
 z is not in the cloud
The relaxation of edge e
updates distance d(z) as
follows:
d(z)  min{d(z),d(u) + weight(e)}
d(z) = 75
d(u) = 50
z
s
u
d(z) = 60
d(u) = 50
z
s
u
e
e
AAD CSE SRMAP 9
Example
C
B
A
E
D
F
0
4
2
8
 
4
8
7 1
2 5
2
3 9
C
B
A
E
D
F
0
3
2
8
5 11
4
8
7 1
2 5
2
3 9
C
B
A
E
D
F
0
3
2
8
5 8
4
8
7 1
2 5
2
3 9
C
B
A
E
D
F
0
3
2
7
5 8
4
8
7 1
2 5
2
3 9
AAD CSE SRMAP 10
Example (cont.)
C
B
A
E
D
F
0
3
2
7
5 8
4
8
7 1
2 5
2
3 9
C
B
A
E
D
F
0
3
2
7
5 8
4
8
7 1
2 5
2
3 9
AAD CSE SRMAP 11
Dijkstra’s Algorithm
A priority queue stores
the vertices outside the
cloud
 Key: distance
 Element: vertex
Locator-based methods
 insert(k,e) returns a
locator
 replaceKey(l,k) changes
the key of an item
We store two labels
with each vertex:
 Distance (d(v) label)
 locator in priority
queue
Algorithm DijkstraDistances(G, s)
Q  new heap-based priority queue
for all v  G.vertices()
if v = s
setDistance(v, 0)
else
setDistance(v, )
l  Q.insert(getDistance(v), v)
setLocator(v,l)
while Q.isEmpty()
u  Q.removeMin()
for all e  G.incidentEdges(u)
{ relax edge e }
z  G.opposite(u,e)
r  getDistance(u) + weight(e)
if r < getDistance(z)
setDistance(z,r)
Q.replaceKey(getLocator(z),r)
AAD CSE SRMAP 12
Analysis
Graph operations
 Method incidentEdges is called once for each vertex
Label operations
 We set/get the distance and locator labels of vertex z O(deg(z)) times
 Setting/getting a label takes O(1) time
Priority queue operations
 Each vertex is inserted once into and removed once from the priority
queue, where each insertion or removal takes O(log n) time
 The key of a vertex in the priority queue is modified at most deg(w)
times, where each key change takes O(log n) time
Dijkstra’s algorithm runs in O((n + m) log n) time provided the
graph is represented by the adjacency list structure
 Recall that Sv deg(v) = 2m
The running time can also be expressed as O(m log n) since the
graph is connected
AAD CSE SRMAP 13
Extension
Using the template
method pattern, we
can extend Dijkstra’s
algorithm to return a
tree of shortest paths
from the start vertex
to all other vertices
We store with each
vertex a third label:
 parent edge in the
shortest path tree
In the edge relaxation
step, we update the
parent label
Algorithm DijkstraShortestPathsTree(G, s)
…
for all v  G.vertices()
…
setParent(v, )
…
for all e  G.incidentEdges(u)
{ relax edge e }
z  G.opposite(u,e)
r  getDistance(u) + weight(e)
if r < getDistance(z)
setDistance(z,r)
setParent(z,e)
Q.replaceKey(getLocator(z),r)
AAD CSE SRMAP 14
Why Dijkstra’s Algorithm
Works
Dijkstra’s algorithm is based on the greedy
method. It adds vertices by increasing distance.
C
B
A
E
D
F
0
3
2
7
5 8
4
8
7 1
2 5
2
3 9
 Suppose it didn’t find all shortest
distances. Let F be the first wrong
vertex the algorithm processed.
 When the previous node, D, on the
true shortest path was considered,
its distance was correct.
 But the edge (D,F) was relaxed at
that time!
 Thus, so long as d(F)>d(D), F’s
distance cannot be wrong. That is,
there is no wrong vertex.
AAD CSE SRMAP 15
Why It Doesn’t Work for
Negative-Weight Edges
 If a node with a negative
incident edge were to be added
late to the cloud, it could mess
up distances for vertices already
in the cloud.
C
B
A
E
D
F
0
4
5
7
5 9
4
8
7 1
2 5
6
0 -8
Dijkstra’s algorithm is based on the greedy
method. It adds vertices by increasing distance.
C’s true distance is 1, but
it is already in the cloud
with d(C)=5!
All-Pairs Shortest Paths
From all nodes {
To All nodes{
Through all nodes{
Improve the distances }}}
AAD CSE SRMAP 16
AAD CSE SRMAP 17
All-Pairs Shortest Paths
Find the distance
between every pair of
vertices in a weighted
directed graph G.
We can make n calls to
Dijkstra’s algorithm (if no
negative edges), which
takes O(nmlog n) time.
Likewise, n calls to
Bellman-Ford would take
O(n2m) time.
We can achieve O(n3)
time using dynamic
programming (similar to
the Floyd-Warshall
algorithm).
Algorithm AllPair(G) {assumes vertices 1,…,n}
for all vertex pairs (i,j)
if i = j
D0[i,i]  0
else if (i,j) is an edge in G
D0[i,j]  weight of edge (i,j)
else
D0[i,j]  + 
for k  1 to n do
for i  1 to n do
for j  1 to n do
Dk[i,j]  min{Dk-1[i,j], Dk-1[i,k]+Dk-1[k,j]}
return Dn
k
j
i
Uses only vertices
numbered 1,…,k-1 Uses only vertices
numbered 1,…,k-1
Uses only vertices numbered 1,…,k
(compute weight of this edge)

More Related Content

Similar to AAD_Lec-3-B-ShortestPaths.ppt of design and analysis of algorithm

Single source shortes path in dag
Single source shortes path in dagSingle source shortes path in dag
Single source shortes path in dag
Kiran K
 
Trees amd properties slide for presentaton
Trees amd properties slide for presentatonTrees amd properties slide for presentaton
Trees amd properties slide for presentaton
SHARANSASI1
 
Temporal graph
Temporal graphTemporal graph
Temporal graph
Vinay Sarda
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docx
SeethaDinesh
 
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
Khoa Mac Tu
 
Optimisation random graph presentation
Optimisation random graph presentationOptimisation random graph presentation
Optimisation random graph presentation
Venkat Sai Sharath Mudhigonda
 
04 greedyalgorithmsii
04 greedyalgorithmsii04 greedyalgorithmsii
04 greedyalgorithmsii
LENIN Quintero
 
Daa chpater14
Daa chpater14Daa chpater14
Daa chpater14
B.Kirron Reddi
 
Graphs: Finding shortest paths
Graphs: Finding shortest pathsGraphs: Finding shortest paths
Graphs: Finding shortest paths
Fulvio Corno
 
Algorithm to count number of disjoint paths
Algorithm to count number of disjoint pathsAlgorithm to count number of disjoint paths
Algorithm to count number of disjoint paths
Sujith Jay Nair
 
Ppt 1
Ppt 1Ppt 1
Topological Sort
Topological SortTopological Sort
Topological Sort
Dr Sandeep Kumar Poonia
 
Randomized algorithms all pairs shortest path
Randomized algorithms  all pairs shortest pathRandomized algorithms  all pairs shortest path
Randomized algorithms all pairs shortest path
Mohammad Akbarizadeh
 
single source shorest path
single source shorest pathsingle source shorest path
single source shorest path
sowfi
 
Module 3- transport_layer .pptx
Module 3- transport_layer           .pptxModule 3- transport_layer           .pptx
Module 3- transport_layer .pptx
hariprasad279825
 
shortestpathalgorithm-180109112405 (1).pdf
shortestpathalgorithm-180109112405 (1).pdfshortestpathalgorithm-180109112405 (1).pdf
shortestpathalgorithm-180109112405 (1).pdf
zefergaming
 

Similar to AAD_Lec-3-B-ShortestPaths.ppt of design and analysis of algorithm (20)

Single source shortes path in dag
Single source shortes path in dagSingle source shortes path in dag
Single source shortes path in dag
 
Trees amd properties slide for presentaton
Trees amd properties slide for presentatonTrees amd properties slide for presentaton
Trees amd properties slide for presentaton
 
Temporal graph
Temporal graphTemporal graph
Temporal graph
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docx
 
Dijkstra
DijkstraDijkstra
Dijkstra
 
d
dd
d
 
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
 
Optimisation random graph presentation
Optimisation random graph presentationOptimisation random graph presentation
Optimisation random graph presentation
 
04 greedyalgorithmsii
04 greedyalgorithmsii04 greedyalgorithmsii
04 greedyalgorithmsii
 
Weighted graphs
Weighted graphsWeighted graphs
Weighted graphs
 
Daa chpater14
Daa chpater14Daa chpater14
Daa chpater14
 
Graphs: Finding shortest paths
Graphs: Finding shortest pathsGraphs: Finding shortest paths
Graphs: Finding shortest paths
 
Algorithm to count number of disjoint paths
Algorithm to count number of disjoint pathsAlgorithm to count number of disjoint paths
Algorithm to count number of disjoint paths
 
Ppt 1
Ppt 1Ppt 1
Ppt 1
 
Topological Sort
Topological SortTopological Sort
Topological Sort
 
Randomized algorithms all pairs shortest path
Randomized algorithms  all pairs shortest pathRandomized algorithms  all pairs shortest path
Randomized algorithms all pairs shortest path
 
single source shorest path
single source shorest pathsingle source shorest path
single source shorest path
 
Module 3- transport_layer .pptx
Module 3- transport_layer           .pptxModule 3- transport_layer           .pptx
Module 3- transport_layer .pptx
 
Network Theory
Network TheoryNetwork Theory
Network Theory
 
shortestpathalgorithm-180109112405 (1).pdf
shortestpathalgorithm-180109112405 (1).pdfshortestpathalgorithm-180109112405 (1).pdf
shortestpathalgorithm-180109112405 (1).pdf
 

Recently uploaded

Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 

Recently uploaded (20)

Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 

AAD_Lec-3-B-ShortestPaths.ppt of design and analysis of algorithm

  • 1. AAD CSE SRMAP 1 Shortest Paths C B A E D F 0 3 2 8 5 8 4 8 7 1 2 5 2 3 9
  • 2. AAD CSE SRMAP 2 Weighted Graphs In a weighted graph, each edge has an associated numerical value, called the weight of the edge Edge weights may represent, distances, costs, etc. Example:  In a flight route graph, the weight of an edge represents the distance in miles between the endpoint airports ORD PVD MIA DFW SFO LAX LGA HNL
  • 3. AAD CSE SRMAP 3 Shortest Path Problem Given a weighted graph and two vertices u and v, we want to find a path of minimum total weight between u and v.  Length of a path is the sum of the weights of its edges. Example:  Shortest path between Providence and Honolulu Applications  Internet packet routing  Flight reservations  Driving directions ORD PVD MIA DFW SFO LAX LGA HNL
  • 4. AAD CSE SRMAP 4 Shortest Path Properties Property 1: A subpath of a shortest path is itself a shortest path Property 2: There is a tree of shortest paths from a start vertex to all the other vertices Example: Tree of shortest paths from Providence ORD PVD MIA DFW SFO LAX LGA HNL
  • 5. Dijkstra’s Algorithm U  Designated node Set1  Remaining nodes Repeat { In the mapping between U and Set1 find V which is the minimum weight(distance) vertex from U. Remove V from Set1. Improve the weights(distances) from U to all other nodes through V } Until set1 is empty AAD CSE SRMAP 5
  • 7. AAD CSE SRMAP 7 Dijkstra’s Algorithm The distance of a vertex v from a vertex s is the length of a shortest path between s and v Dijkstra’s algorithm computes the distances of all the vertices from a given start vertex s Assumptions:  the graph is connected  the edges are undirected  the edge weights are nonnegative We grow a “cloud” of vertices, beginning with s and eventually covering all the vertices We store with each vertex v a label d(v) representing the distance of v from s in the subgraph consisting of the cloud and its adjacent vertices At each step  We add to the cloud the vertex u outside the cloud with the smallest distance label, d(u)  We update the labels of the vertices adjacent to u
  • 8. AAD CSE SRMAP 8 Edge Relaxation Consider an edge e = (u,z) such that  u is the vertex most recently added to the cloud  z is not in the cloud The relaxation of edge e updates distance d(z) as follows: d(z)  min{d(z),d(u) + weight(e)} d(z) = 75 d(u) = 50 z s u d(z) = 60 d(u) = 50 z s u e e
  • 9. AAD CSE SRMAP 9 Example C B A E D F 0 4 2 8   4 8 7 1 2 5 2 3 9 C B A E D F 0 3 2 8 5 11 4 8 7 1 2 5 2 3 9 C B A E D F 0 3 2 8 5 8 4 8 7 1 2 5 2 3 9 C B A E D F 0 3 2 7 5 8 4 8 7 1 2 5 2 3 9
  • 10. AAD CSE SRMAP 10 Example (cont.) C B A E D F 0 3 2 7 5 8 4 8 7 1 2 5 2 3 9 C B A E D F 0 3 2 7 5 8 4 8 7 1 2 5 2 3 9
  • 11. AAD CSE SRMAP 11 Dijkstra’s Algorithm A priority queue stores the vertices outside the cloud  Key: distance  Element: vertex Locator-based methods  insert(k,e) returns a locator  replaceKey(l,k) changes the key of an item We store two labels with each vertex:  Distance (d(v) label)  locator in priority queue Algorithm DijkstraDistances(G, s) Q  new heap-based priority queue for all v  G.vertices() if v = s setDistance(v, 0) else setDistance(v, ) l  Q.insert(getDistance(v), v) setLocator(v,l) while Q.isEmpty() u  Q.removeMin() for all e  G.incidentEdges(u) { relax edge e } z  G.opposite(u,e) r  getDistance(u) + weight(e) if r < getDistance(z) setDistance(z,r) Q.replaceKey(getLocator(z),r)
  • 12. AAD CSE SRMAP 12 Analysis Graph operations  Method incidentEdges is called once for each vertex Label operations  We set/get the distance and locator labels of vertex z O(deg(z)) times  Setting/getting a label takes O(1) time Priority queue operations  Each vertex is inserted once into and removed once from the priority queue, where each insertion or removal takes O(log n) time  The key of a vertex in the priority queue is modified at most deg(w) times, where each key change takes O(log n) time Dijkstra’s algorithm runs in O((n + m) log n) time provided the graph is represented by the adjacency list structure  Recall that Sv deg(v) = 2m The running time can also be expressed as O(m log n) since the graph is connected
  • 13. AAD CSE SRMAP 13 Extension Using the template method pattern, we can extend Dijkstra’s algorithm to return a tree of shortest paths from the start vertex to all other vertices We store with each vertex a third label:  parent edge in the shortest path tree In the edge relaxation step, we update the parent label Algorithm DijkstraShortestPathsTree(G, s) … for all v  G.vertices() … setParent(v, ) … for all e  G.incidentEdges(u) { relax edge e } z  G.opposite(u,e) r  getDistance(u) + weight(e) if r < getDistance(z) setDistance(z,r) setParent(z,e) Q.replaceKey(getLocator(z),r)
  • 14. AAD CSE SRMAP 14 Why Dijkstra’s Algorithm Works Dijkstra’s algorithm is based on the greedy method. It adds vertices by increasing distance. C B A E D F 0 3 2 7 5 8 4 8 7 1 2 5 2 3 9  Suppose it didn’t find all shortest distances. Let F be the first wrong vertex the algorithm processed.  When the previous node, D, on the true shortest path was considered, its distance was correct.  But the edge (D,F) was relaxed at that time!  Thus, so long as d(F)>d(D), F’s distance cannot be wrong. That is, there is no wrong vertex.
  • 15. AAD CSE SRMAP 15 Why It Doesn’t Work for Negative-Weight Edges  If a node with a negative incident edge were to be added late to the cloud, it could mess up distances for vertices already in the cloud. C B A E D F 0 4 5 7 5 9 4 8 7 1 2 5 6 0 -8 Dijkstra’s algorithm is based on the greedy method. It adds vertices by increasing distance. C’s true distance is 1, but it is already in the cloud with d(C)=5!
  • 16. All-Pairs Shortest Paths From all nodes { To All nodes{ Through all nodes{ Improve the distances }}} AAD CSE SRMAP 16
  • 17. AAD CSE SRMAP 17 All-Pairs Shortest Paths Find the distance between every pair of vertices in a weighted directed graph G. We can make n calls to Dijkstra’s algorithm (if no negative edges), which takes O(nmlog n) time. Likewise, n calls to Bellman-Ford would take O(n2m) time. We can achieve O(n3) time using dynamic programming (similar to the Floyd-Warshall algorithm). Algorithm AllPair(G) {assumes vertices 1,…,n} for all vertex pairs (i,j) if i = j D0[i,i]  0 else if (i,j) is an edge in G D0[i,j]  weight of edge (i,j) else D0[i,j]  +  for k  1 to n do for i  1 to n do for j  1 to n do Dk[i,j]  min{Dk-1[i,j], Dk-1[i,k]+Dk-1[k,j]} return Dn k j i Uses only vertices numbered 1,…,k-1 Uses only vertices numbered 1,…,k-1 Uses only vertices numbered 1,…,k (compute weight of this edge)

Editor's Notes

  1. 5/8/2024 7:23 AM