SlideShare a Scribd company logo
1 of 48
Shortest paths in graphs




                           1
Shortest path IN   directed graph




                                    2
Shortest paths




                 3
Variants
• Single-source: Find shortest paths from a
  given source vertex s in V to every vertex
  v in V.
• Single-destination: Find shortest paths to
  a given destination vertex.
• Single-pair: Find shortest path from u to
  v. No way known that’s better in worst case
  than solving single-source.
• All-pairs: Find shortest path from u to v
  for all u, v in V. We’ll see algorithms for all-
  pairs in the next chapter.

                                                 4
Negative-weight edges

• OK, as long as no negative-weight cycles
  are reachable from the source.
• •If we have a negative-weight cycle, we can
  just keep going around it, and get
•     w(s, v) = −∞for all v on the cycle.
• But OK if the negative-weight cycle is not
  reachable from the source.
• Some algorithms work only if there are no
  negative-weight edges in the graph.

                                            5
Lemma 1)
•   Optimal substructure lemma: Any sub-path of
    a shortest path is a shortest path.
•   Shortest paths can’t contain cycles:
      proofs: rather trivial.

•   We use the d[v] array at all times
INIT-SINGLE-SOURCE(V, s)
{
    for each v in V{
       d[v]←∞
       π[v] ← NIL
     }
    d[s] ← 0
}
                                                  6
Relaxing
RELAX(u, v, w){
  if d[v] > d[u] + w(u, v) then{
      d[v] ← d[u] + w(u, v)
      π[v]← u
  }
}
     For all the single-source shortest-paths
     algorithms we’ll do the following:
     • start by calling INIT-SINGLE-SOURCE,
     • then relax edges.
     The algorithms differ in the order and
     how many times they relax each edge.

                                            7
Lemma 2) Triangle inequality

Claim: For all (u, v) in E, we have
            δ(s, v) ≤ δ(s, u) + w(u, v).
Proof: Weight of shortest path s ---> v is
          ≤ weight of any path s --->v.
Path s ---> u → v is a path s --->v, and if we
  use a shortest path s ---> u, its weight is
  δ(s, u) + w(u, v).




                                                 8
Lemma 3) Upper-bound property
1) Always have d[v] ≥ δ(s, v) for all v.
2) Once d[v] = δ(s, v), it never changes.
Proof Initially true.
• Suppose there exists a vertex such that
  d[v] < δ(s, v). Without loss of generality, v is first
  vertex for which this happens.
• Let u be the vertex that causes d[v] to change.
  Then d[v] = d[u] + w(u, v).
So, d[v] < δ(s, v)
    ≤ δ(s, u) + w(u, v) (triangle inequality)
    ≤ d[u] + w(u, v) (v is first violation)
  d[v] < d[u] + w(u, v) .
Contradicts d[v] = d[u] + w(u, v).
                                                           9
Lemma 4: Convergence property

If s ---> u → v is a shortest path and
 d[u] = δ(s, u), and we call RELAX(u,v,w), then
 d[v] = δ(s, v) afterward.
Proof: After relaxation:
d[v] ≤ d[u] + w(u, v) (RELAX code)
=      δ(s, u) + w(u, v) (assumption)
=     δ(s, v) (Optimal substructure lemma)
Since d[v] ≥ δ(s, v), must have d[v] = δ(s, v).


                                              10
(Lemma 5) Path relaxation property

Let p = v0, v1, . . . , vk be a shortest path from s = v0
  to vk .
If we relax, in order, (v0, v1), (v1, v2), . . . , (Vk−1,
  Vk), even intermixed with other relaxations,
then d[Vk ] = δ(s, Vk ).
Proof Induction to show that d[vi ] = δ(s, vi ) after
  (vi−1, vi ) is relaxed.
Basis: i = 0. Initially, d[v0] = 0 = δ(s, v0) = δ(s, s).
Inductive step: Assume d[vi−1] = δ(s, vi−1). Relax
  (vi−1, vi ). By convergence property, d[vi ] = δ(s,
  vi ) afterward and d[vi ] never changes.

                                                            11
The Bellman-Ford algorithm

• Allows negative-weight edges.
• Computes d[v] and π[v] for all v inV.
• Returns TRUE if no negative-weight cycles
  reachable from s, FALSE otherwise.




                                              12
Bellman-ford
BELLMAN-FORD(V, E, w, s){
     INIT-SINGLE-SOURCE(V, s)
     for i ← 1 to |V| − 1
            for each edge (u, v) in E
                   RELAX(u, v, w)
    for each edge (u, v) in E
          if d[v] > d[u] + w(u, v)
              return FALSE
   return TRUE
}
Time: O(V*E)= O(V^3) in the worst case.

                                          13
Correctness of Belman-Ford
Let v be reachable from s, and let p = {v0, v1, . . . , vk}
   be a shortest path from s  v,
               where v0 = s and vk = v.
• Since p is acyclic, it has ≤ |V| − 1 edges, so k ≤|V|−1.
Each iteration of the for loop relaxes all edges:
• First iteration relaxes (v0, v1).
• Second iteration relaxes (v1, v2).
• kth iteration relaxes (vk−1, vk).
By the path-relaxation property,
       d[v] = d[vk ] = δ(s, vk ) = δ(s, v).

                                                         14
How about the TRUE/FALSE return value?

• Suppose there is no negative-weight cycle
  reachable from s.
At termination, for all (u, v) in E,
   d[v] = δ(s, v)
        ≤ δ(s, u) + w(u, v) (triangle inequality)
        = d[u] + w(u, v) .
So BELLMAN-FORD returns TRUE.




                                                    15
Proof continues




                  16
Single-source shortest paths in a directed
               acyclic graph
DAG-SHORTEST-PATHS(V, E, w, s)
{
   topologically sort the vertices
   INIT-SINGLE-SOURCE(V, s)
   for each vertex u, in topologically order
      for each vertex v in Adj[u]
           RELAX(u, v, w)
}

                                               17
18
Dijkstra’s algorithm

• No negative-weight edges.
• Essentially a weighted version of breadth-
  first search.
• Instead of a FIFO queue, uses a priority
  queue.
• Keys are shortest-path weights (d[v]).
• Have two sets of vertices:
     S = vertices whose final shortest-path
          weights are determined,
     Q = priority queue = (was V − S. not
 anymore)
                                               19
Dijkstra algorithm
DIJKSTRA(V, E, w, s){
  INIT-SINGLE-SOURCE(V, s)
  Q←s
  while Q = ∅{
      u ← EXTRACT-MIN(Q)
       for each vertex v in Adj [u]{
             if (d[v] == infinity){
                       RELAX(u,v,w); (d[v]=d[u]+w[u,v])
                      enqueue(v,Q)
             }
            elseif(v inside Q)
                 RELAX(u,v,w);
                 change priority(Q,v);
    }
}                                                         20
Dijkstra's




             21
Dijkstra's




             22
Best-first search
• Best first search – an algorithm scheme:
   • Have a queue (open-list) of nodes. That is of
     generated but no expanded.
   • List is sorted according to a cost function.
   • Add the start node to the queue
   =============================
   while queue not empty{ (expansion cycle):
      • Remove the best node from the queue
         • Goal-test (If goal, stop)
      • Add its children to the queue
         • Take care of duplicates {relax}

  }
                                                     23
Best-first search
• Best-first search algorithm differ in their
  cost function, labeled f(n)
   • and maybe some other technical details are
     different too.
   • There are many implementation variants.
• Breadth-first search: f(n) = number of edges in the tree
• Dijsktra’s algorithm: f(n) = weight of the edges.
   • Also called Unifrom cost search (UCS). Should be called
      wegihted-breadth-first search (WBRFS).
• A* Algorithm: f(n)=g(n)+h(n). We will study this next year.
• Other special cases too.


                                                               24
Best-first search
• In general a node n in best-first search is
  going through the following three stages:
  • Unknown It was not yet generated.
    • AKA (free, white, unseen…)
  • In queue n was generated and it is in the queue.
    • AKA (Opened, generated-not-expanded, touched,
      visited, gray, seen-not-handled)
  • Expanded (AKA, handled, finished, black,
    closed)



                                                      25
Correctness proof for Dijkstra
• 1)  Queue is a perimeter of nodes around s.
   • Proof by induction:
        • Initially true. S is a perimeter around itself.
        • Generalization: A node was removed, but all its negihbours were added.
   • Consequence: every path to the goal (including any shortest path)
     has a representative node in queue
• 2) The cost of a node in queue can only be increased.
   •   Proof: Since all edges are non-negative. Cost can only be increased.

• 3) When node is chosen for expansion, its cost is the best in the
  queue.
• Consequence: If there is a better path there must be an ancestor
  in the q ueue (1) with a better cost (2). This is impossible. (3)




                                                                                   26
Correctness proof for Dijkstra
• B will only be expanded if there is no ancestor
  of B with small value.



         S                        S
        9     8                  4
    A                        A         8

        3     B                  3     B

                    C                       C
                                                    27
Correctness proof for Dijkstra
• What happens if edges are negative?
  • Item 2 (lower bound) is no longer true and therefore -
  • Costs are not a lower bound and can be later
    decreased. Optimality is not guaranteed.

• When node A is selected,
it does not have the       C
shortest path to it.                2
• Why? Because via B we              A -4 B
have a shorter path
                                      5   8
• Could be corrected if we
re-insert nodes into the                    S
queue
                                                         28
Proof according to book:
very hard and not necessary (Do not learn)




                                             29
30
Proof




        31
All pairs Shortest paths




                           32
33
34
35
APSP




       36
Matrixes
Observation: EXTEND is like matrix
  multiplication:
L→A
W→B
L’ → C
min → +
+→·
∞→0


                                     37
C=BxA  L’=LxW
                 38
Matrix Multiplication




                        39
All pairs shortest paths
• Directed graph G = (V, E), weight w : E → R,
  |V | = n .
Goal: create an n × n matrix of shortest-path
  distances δ(u, v).
• Could run BELLMAN-FORD once from each
  vertex
• If no negative-weight edges, could run
  Dijkstra’s algorithm once from each
  vertex:
• We’ll see how to do in O(V3) in all cases,
  with no fancy data structure.
                                             40
Floyd-Warshal algorithm
For path p = {v1, v2, . . . , vl} , an intermediate
vertex is any vertex of p other than v1 or vl .
• Let dij{k} = shortest-path weight of any
  path i  j with all intermediate vertices
  from {1, 2, . . . , k}.

Consider a shortest path p:i j with all
 intermediate vertices in {1, 2, . . . , k}:



                                                  41
Floyd-Warshal




                42
Floyd-Warshal




                43
The algorithm




                44
Proof for floyd warshal
• Invariant: for each K we have the shortest
  path from each pair with intermediate
  vertices {1,2, .. K}
Proof is an easy induction.
• Basic step: use D(0)
• Induction step: look at the last line!!
• Time: O(v^3)




                                           45
Transitive closure
Given G = (V, E), directed.
Compute G∗ = (V, E∗).
• E∗ = {(i, j ) : there is a path i  j in G}.
Could assign weight of 1 to each edge, then
  run FLOYD-WARSHALL.
• If di j < n, then there is a path i  j .
• Otherwise, di j =∞ and there is no path.




                                                 46
47
Time: O(n^3), but simpler operations than
FLOYD-WARSHALL.                           48

More Related Content

What's hot

Single source shortes path in dag
Single source shortes path in dagSingle source shortes path in dag
Single source shortes path in dagKiran K
 
lecture 21
lecture 21lecture 21
lecture 21sajinsc
 
Bellman ford
Bellman fordBellman ford
Bellman fordKiran K
 
Algorithm Design and Complexity - Course 7
Algorithm Design and Complexity - Course 7Algorithm Design and Complexity - Course 7
Algorithm Design and Complexity - Course 7Traian Rebedea
 
lecture 20
lecture 20lecture 20
lecture 20sajinsc
 
Johnson's algorithm
Johnson's algorithmJohnson's algorithm
Johnson's algorithmKiran K
 
2.6 all pairsshortestpath
2.6 all pairsshortestpath2.6 all pairsshortestpath
2.6 all pairsshortestpathKrish_ver2
 
Algorithm Design and Complexity - Course 9
Algorithm Design and Complexity - Course 9Algorithm Design and Complexity - Course 9
Algorithm Design and Complexity - Course 9Traian Rebedea
 
String Matching with Finite Automata and Knuth Morris Pratt Algorithm
String Matching with Finite Automata and Knuth Morris Pratt AlgorithmString Matching with Finite Automata and Knuth Morris Pratt Algorithm
String Matching with Finite Automata and Knuth Morris Pratt AlgorithmKiran K
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithmRuchika Sinha
 
Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8Traian Rebedea
 
Algorithms of graph
Algorithms of graphAlgorithms of graph
Algorithms of graphgetacew
 
Floyd warshall-algorithm
Floyd warshall-algorithmFloyd warshall-algorithm
Floyd warshall-algorithmMalinga Perera
 
Skiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivitySkiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivityzukun
 
Algorithm Design and Complexity - Course 12
Algorithm Design and Complexity - Course 12Algorithm Design and Complexity - Course 12
Algorithm Design and Complexity - Course 12Traian Rebedea
 

What's hot (20)

Single source shortes path in dag
Single source shortes path in dagSingle source shortes path in dag
Single source shortes path in dag
 
lecture 21
lecture 21lecture 21
lecture 21
 
Bellman ford
Bellman fordBellman ford
Bellman ford
 
21 All Pairs Shortest Path
21 All Pairs Shortest Path21 All Pairs Shortest Path
21 All Pairs Shortest Path
 
Algorithm Design and Complexity - Course 7
Algorithm Design and Complexity - Course 7Algorithm Design and Complexity - Course 7
Algorithm Design and Complexity - Course 7
 
lecture 20
lecture 20lecture 20
lecture 20
 
Johnson's algorithm
Johnson's algorithmJohnson's algorithm
Johnson's algorithm
 
2.6 all pairsshortestpath
2.6 all pairsshortestpath2.6 all pairsshortestpath
2.6 all pairsshortestpath
 
Algorithm Design and Complexity - Course 9
Algorithm Design and Complexity - Course 9Algorithm Design and Complexity - Course 9
Algorithm Design and Complexity - Course 9
 
String Matching with Finite Automata and Knuth Morris Pratt Algorithm
String Matching with Finite Automata and Knuth Morris Pratt AlgorithmString Matching with Finite Automata and Knuth Morris Pratt Algorithm
String Matching with Finite Automata and Knuth Morris Pratt Algorithm
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 
Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8
 
Topological sorting
Topological sortingTopological sorting
Topological sorting
 
Daa chpater14
Daa chpater14Daa chpater14
Daa chpater14
 
Algorithms of graph
Algorithms of graphAlgorithms of graph
Algorithms of graph
 
Floyd warshall-algorithm
Floyd warshall-algorithmFloyd warshall-algorithm
Floyd warshall-algorithm
 
Compactrouting
CompactroutingCompactrouting
Compactrouting
 
Skiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivitySkiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivity
 
Algorithm Design and Complexity - Course 12
Algorithm Design and Complexity - Course 12Algorithm Design and Complexity - Course 12
Algorithm Design and Complexity - Course 12
 
Shortest path
Shortest pathShortest path
Shortest path
 

Viewers also liked

Top-k shortest path
Top-k shortest pathTop-k shortest path
Top-k shortest pathredhatdb
 
Dijkstra's algorithm
Dijkstra's algorithmDijkstra's algorithm
Dijkstra's algorithmgsp1294
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithmSrikrishnan Suresh
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with DataSeth Familian
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

Viewers also liked (7)

Spsp fw
Spsp fwSpsp fw
Spsp fw
 
Top-k shortest path
Top-k shortest pathTop-k shortest path
Top-k shortest path
 
Dijkstra's algorithm
Dijkstra's algorithmDijkstra's algorithm
Dijkstra's algorithm
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithm
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with Data
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similar to Shortest Path Algorithms in Graphs

Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10Traian Rebedea
 
14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpathSSE_AndyLi
 
bellman-ford Theorem.ppt
bellman-ford Theorem.pptbellman-ford Theorem.ppt
bellman-ford Theorem.pptSaimaShaheen14
 
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 pathsSujith Jay Nair
 
04 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x204 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x2MuradAmn
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docxSeethaDinesh
 
Shortest Paths Part 2: Negative Weights and All-pairs
Shortest Paths Part 2: Negative Weights and All-pairsShortest Paths Part 2: Negative Weights and All-pairs
Shortest Paths Part 2: Negative Weights and All-pairsBenjamin Sach
 
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in indiaEdhole.com
 
Lecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdfLecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdfiftakhar8
 

Similar to Shortest Path Algorithms in Graphs (20)

Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10
 
14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath
 
bellman-ford Theorem.ppt
bellman-ford Theorem.pptbellman-ford Theorem.ppt
bellman-ford Theorem.ppt
 
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
 
Dijkstra c
Dijkstra cDijkstra c
Dijkstra c
 
04 greedyalgorithmsii
04 greedyalgorithmsii04 greedyalgorithmsii
04 greedyalgorithmsii
 
04 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x204 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x2
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docx
 
Unit ix graph
Unit   ix    graph Unit   ix    graph
Unit ix graph
 
Dijkstra.ppt
Dijkstra.pptDijkstra.ppt
Dijkstra.ppt
 
Dijksatra
DijksatraDijksatra
Dijksatra
 
Graph 3
Graph 3Graph 3
Graph 3
 
Shortest Paths Part 2: Negative Weights and All-pairs
Shortest Paths Part 2: Negative Weights and All-pairsShortest Paths Part 2: Negative Weights and All-pairs
Shortest Paths Part 2: Negative Weights and All-pairs
 
dijkstraC.ppt
dijkstraC.pptdijkstraC.ppt
dijkstraC.ppt
 
Unit 9 graph
Unit   9 graphUnit   9 graph
Unit 9 graph
 
19-graph1 (1).ppt
19-graph1 (1).ppt19-graph1 (1).ppt
19-graph1 (1).ppt
 
chapter24.ppt
chapter24.pptchapter24.ppt
chapter24.ppt
 
Programming Exam Help
Programming Exam Help Programming Exam Help
Programming Exam Help
 
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in india
 
Lecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdfLecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdf
 

Recently uploaded

Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 

Recently uploaded (20)

Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 

Shortest Path Algorithms in Graphs

  • 1. Shortest paths in graphs 1
  • 2. Shortest path IN directed graph 2
  • 4. Variants • Single-source: Find shortest paths from a given source vertex s in V to every vertex v in V. • Single-destination: Find shortest paths to a given destination vertex. • Single-pair: Find shortest path from u to v. No way known that’s better in worst case than solving single-source. • All-pairs: Find shortest path from u to v for all u, v in V. We’ll see algorithms for all- pairs in the next chapter. 4
  • 5. Negative-weight edges • OK, as long as no negative-weight cycles are reachable from the source. • •If we have a negative-weight cycle, we can just keep going around it, and get • w(s, v) = −∞for all v on the cycle. • But OK if the negative-weight cycle is not reachable from the source. • Some algorithms work only if there are no negative-weight edges in the graph. 5
  • 6. Lemma 1) • Optimal substructure lemma: Any sub-path of a shortest path is a shortest path. • Shortest paths can’t contain cycles: proofs: rather trivial. • We use the d[v] array at all times INIT-SINGLE-SOURCE(V, s) { for each v in V{ d[v]←∞ π[v] ← NIL } d[s] ← 0 } 6
  • 7. Relaxing RELAX(u, v, w){ if d[v] > d[u] + w(u, v) then{ d[v] ← d[u] + w(u, v) π[v]← u } } For all the single-source shortest-paths algorithms we’ll do the following: • start by calling INIT-SINGLE-SOURCE, • then relax edges. The algorithms differ in the order and how many times they relax each edge. 7
  • 8. Lemma 2) Triangle inequality Claim: For all (u, v) in E, we have δ(s, v) ≤ δ(s, u) + w(u, v). Proof: Weight of shortest path s ---> v is ≤ weight of any path s --->v. Path s ---> u → v is a path s --->v, and if we use a shortest path s ---> u, its weight is δ(s, u) + w(u, v). 8
  • 9. Lemma 3) Upper-bound property 1) Always have d[v] ≥ δ(s, v) for all v. 2) Once d[v] = δ(s, v), it never changes. Proof Initially true. • Suppose there exists a vertex such that d[v] < δ(s, v). Without loss of generality, v is first vertex for which this happens. • Let u be the vertex that causes d[v] to change. Then d[v] = d[u] + w(u, v). So, d[v] < δ(s, v) ≤ δ(s, u) + w(u, v) (triangle inequality) ≤ d[u] + w(u, v) (v is first violation)  d[v] < d[u] + w(u, v) . Contradicts d[v] = d[u] + w(u, v). 9
  • 10. Lemma 4: Convergence property If s ---> u → v is a shortest path and d[u] = δ(s, u), and we call RELAX(u,v,w), then d[v] = δ(s, v) afterward. Proof: After relaxation: d[v] ≤ d[u] + w(u, v) (RELAX code) = δ(s, u) + w(u, v) (assumption) = δ(s, v) (Optimal substructure lemma) Since d[v] ≥ δ(s, v), must have d[v] = δ(s, v). 10
  • 11. (Lemma 5) Path relaxation property Let p = v0, v1, . . . , vk be a shortest path from s = v0 to vk . If we relax, in order, (v0, v1), (v1, v2), . . . , (Vk−1, Vk), even intermixed with other relaxations, then d[Vk ] = δ(s, Vk ). Proof Induction to show that d[vi ] = δ(s, vi ) after (vi−1, vi ) is relaxed. Basis: i = 0. Initially, d[v0] = 0 = δ(s, v0) = δ(s, s). Inductive step: Assume d[vi−1] = δ(s, vi−1). Relax (vi−1, vi ). By convergence property, d[vi ] = δ(s, vi ) afterward and d[vi ] never changes. 11
  • 12. The Bellman-Ford algorithm • Allows negative-weight edges. • Computes d[v] and π[v] for all v inV. • Returns TRUE if no negative-weight cycles reachable from s, FALSE otherwise. 12
  • 13. Bellman-ford BELLMAN-FORD(V, E, w, s){ INIT-SINGLE-SOURCE(V, s) for i ← 1 to |V| − 1 for each edge (u, v) in E RELAX(u, v, w) for each edge (u, v) in E if d[v] > d[u] + w(u, v) return FALSE return TRUE } Time: O(V*E)= O(V^3) in the worst case. 13
  • 14. Correctness of Belman-Ford Let v be reachable from s, and let p = {v0, v1, . . . , vk} be a shortest path from s  v, where v0 = s and vk = v. • Since p is acyclic, it has ≤ |V| − 1 edges, so k ≤|V|−1. Each iteration of the for loop relaxes all edges: • First iteration relaxes (v0, v1). • Second iteration relaxes (v1, v2). • kth iteration relaxes (vk−1, vk). By the path-relaxation property, d[v] = d[vk ] = δ(s, vk ) = δ(s, v). 14
  • 15. How about the TRUE/FALSE return value? • Suppose there is no negative-weight cycle reachable from s. At termination, for all (u, v) in E, d[v] = δ(s, v) ≤ δ(s, u) + w(u, v) (triangle inequality) = d[u] + w(u, v) . So BELLMAN-FORD returns TRUE. 15
  • 17. Single-source shortest paths in a directed acyclic graph DAG-SHORTEST-PATHS(V, E, w, s) { topologically sort the vertices INIT-SINGLE-SOURCE(V, s) for each vertex u, in topologically order for each vertex v in Adj[u] RELAX(u, v, w) } 17
  • 18. 18
  • 19. Dijkstra’s algorithm • No negative-weight edges. • Essentially a weighted version of breadth- first search. • Instead of a FIFO queue, uses a priority queue. • Keys are shortest-path weights (d[v]). • Have two sets of vertices: S = vertices whose final shortest-path weights are determined, Q = priority queue = (was V − S. not anymore) 19
  • 20. Dijkstra algorithm DIJKSTRA(V, E, w, s){ INIT-SINGLE-SOURCE(V, s) Q←s while Q = ∅{ u ← EXTRACT-MIN(Q) for each vertex v in Adj [u]{ if (d[v] == infinity){ RELAX(u,v,w); (d[v]=d[u]+w[u,v]) enqueue(v,Q) } elseif(v inside Q) RELAX(u,v,w); change priority(Q,v); } } 20
  • 23. Best-first search • Best first search – an algorithm scheme: • Have a queue (open-list) of nodes. That is of generated but no expanded. • List is sorted according to a cost function. • Add the start node to the queue ============================= while queue not empty{ (expansion cycle): • Remove the best node from the queue • Goal-test (If goal, stop) • Add its children to the queue • Take care of duplicates {relax} } 23
  • 24. Best-first search • Best-first search algorithm differ in their cost function, labeled f(n) • and maybe some other technical details are different too. • There are many implementation variants. • Breadth-first search: f(n) = number of edges in the tree • Dijsktra’s algorithm: f(n) = weight of the edges. • Also called Unifrom cost search (UCS). Should be called wegihted-breadth-first search (WBRFS). • A* Algorithm: f(n)=g(n)+h(n). We will study this next year. • Other special cases too. 24
  • 25. Best-first search • In general a node n in best-first search is going through the following three stages: • Unknown It was not yet generated. • AKA (free, white, unseen…) • In queue n was generated and it is in the queue. • AKA (Opened, generated-not-expanded, touched, visited, gray, seen-not-handled) • Expanded (AKA, handled, finished, black, closed) 25
  • 26. Correctness proof for Dijkstra • 1) Queue is a perimeter of nodes around s. • Proof by induction: • Initially true. S is a perimeter around itself. • Generalization: A node was removed, but all its negihbours were added. • Consequence: every path to the goal (including any shortest path) has a representative node in queue • 2) The cost of a node in queue can only be increased. • Proof: Since all edges are non-negative. Cost can only be increased. • 3) When node is chosen for expansion, its cost is the best in the queue. • Consequence: If there is a better path there must be an ancestor in the q ueue (1) with a better cost (2). This is impossible. (3) 26
  • 27. Correctness proof for Dijkstra • B will only be expanded if there is no ancestor of B with small value. S S 9 8 4 A A 8 3 B 3 B C C 27
  • 28. Correctness proof for Dijkstra • What happens if edges are negative? • Item 2 (lower bound) is no longer true and therefore - • Costs are not a lower bound and can be later decreased. Optimality is not guaranteed. • When node A is selected, it does not have the C shortest path to it. 2 • Why? Because via B we A -4 B have a shorter path 5 8 • Could be corrected if we re-insert nodes into the S queue 28
  • 29. Proof according to book: very hard and not necessary (Do not learn) 29
  • 30. 30
  • 31. Proof 31
  • 32. All pairs Shortest paths 32
  • 33. 33
  • 34. 34
  • 35. 35
  • 36. APSP 36
  • 37. Matrixes Observation: EXTEND is like matrix multiplication: L→A W→B L’ → C min → + +→· ∞→0 37
  • 40. All pairs shortest paths • Directed graph G = (V, E), weight w : E → R, |V | = n . Goal: create an n × n matrix of shortest-path distances δ(u, v). • Could run BELLMAN-FORD once from each vertex • If no negative-weight edges, could run Dijkstra’s algorithm once from each vertex: • We’ll see how to do in O(V3) in all cases, with no fancy data structure. 40
  • 41. Floyd-Warshal algorithm For path p = {v1, v2, . . . , vl} , an intermediate vertex is any vertex of p other than v1 or vl . • Let dij{k} = shortest-path weight of any path i  j with all intermediate vertices from {1, 2, . . . , k}. Consider a shortest path p:i j with all intermediate vertices in {1, 2, . . . , k}: 41
  • 45. Proof for floyd warshal • Invariant: for each K we have the shortest path from each pair with intermediate vertices {1,2, .. K} Proof is an easy induction. • Basic step: use D(0) • Induction step: look at the last line!! • Time: O(v^3) 45
  • 46. Transitive closure Given G = (V, E), directed. Compute G∗ = (V, E∗). • E∗ = {(i, j ) : there is a path i  j in G}. Could assign weight of 1 to each edge, then run FLOYD-WARSHALL. • If di j < n, then there is a path i  j . • Otherwise, di j =∞ and there is no path. 46
  • 47. 47
  • 48. Time: O(n^3), but simpler operations than FLOYD-WARSHALL. 48