SlideShare a Scribd company logo
1 of 27
Download to read offline
Lecture 14:
        Shortest Paths
         Steven Skiena

Department of Computer Science
 State University of New York
 Stony Brook, NY 11794–4400

http://www.cs.sunysb.edu/∼skiena
Problem of the Day
Suppose we are given the minimum spanning tree T of a
given graph G (with n vertices and m edges) and a new edge
e = (u, v) of weight w that we will add to G. Give an efficient
algorithm to find the minimum spanning tree of the graph
G + e. Your algorithm should run in O(n) time to receive
full credit, although slower but correct algorithms will receive
partial credit.
Shortest Paths
Finding the shortest path between two nodes in a graph arises
in many different applications:
 • Transportation problems – finding the cheapest way to
   travel between two locations.
 • Motion planning – what is the most natural way for a
   cartoon character to move about a simulated environment.
 • Communications problems – how look will it take for a
   message to get between two places? Which two locations
   are furthest apart, ie. what is the diameter of the network.
Shortest Paths and Sentence Disambiguation
In our work on reconstructing text typed on an (overloaded)
telephone keypad, we had to select which of many possible
interpretations was most likely.
We constructed a graph where the vertices were the possible
words/positions in the sentence, with an edge between
possible neighboring words.
r ` q a h g d e d b a
                       s£©pif2f2c£`                                                        ¡ y x ¡ y
                                                                                            C™2C¥n
                                                                                                #
  $ 5 %6 8
    $        u
      5 %6 7 pt t                              ' 21    u
 $ %
  56 54           t       3       w pv v v       0)      pt t t ' & % (
                                                                 ' %
                                                                   $
                                                                               ’ “” „ g “ l k „ “ i ‰ …‰” …‰
                                                                                £… •€£€’ 2m™•e UjYC•2™h
  $ 5 %6 8                                                                                     #
    $ 5 %6 7                                   ' 21                ' % (
 $ %
  56 54                   3                      0)                 ' %
                                                                      $
       #                      #                   #                     #
                                                                        
                                                                          
     !
                            !                 !       
                                                                      
¨¦ ¤ ¢
§¥£¡                  ¨ ¦ ¤ ¢
                        ©§¥£¡                ¨ ¦ ¤ ¢
                                              ©£¥£¡              ¨ ¦ ¤ ¢
                                                                  ©§¥£¡
                                                                               … “” gf”e … ‘ – ‰” „ “ ˜ … „
                                                                                €‘ •Y£•55£€—d•™C˜ 2£€—–
                                                                                              #
                                                                          
     !
                            !                 !       
                                                                      
¨¦ ¤ ¢
§¥£¡                  ¨ ¦ ¤ ¢
                        ©§¥£¡                ¨ ¦ ¤ ¢
                                              ©£¥£¡              ¨ ¦ ¤ ¢
                                                                  ©§¥£¡
                                                                                   …€‘ “•” “C…€’€YYUˆC€„ ƒ
                                                                                                  ‘‰ ‡ † … ‚
                                                                                                    #
               999 B D R D T Q S Q I R Q I G D D B 99
               @YXWVHUPPFPPFPPHFECA@9                                                           ¡ y x q
                                                                                                 C€2ca
Weighting the Graph

                                          Code C 1        Code C 2    Code C 3
                                         1
                                      P(W1/C 1)                 2
                                                          P(W1/C 2)   P(W13 3)
                                                                          /C


                                                                                          4
                                                                                  P(#/W 1)
                    P(W11/#)
                                         1              2  1
                                                     P(W2/W1)            3
                                      P(W2/C 1)                       P(W2/C 3)

                               P(W21/#)
                       #                                 P(W22 2)
                                                             /C                       #
                               P(W31/#)
                                         1
                                      P(W3/C 1)                       P(W33 3)
                                                                          /C
                    P(W41/#)



                                      P(W41 1)
                                          /C                          P(W43 3)
                                                                          /C




The weight of each edge is a function of the probability that
these two words will be next to each other in a sentence. ‘hive
me’ would be less than ‘give me’, for example.
The final system worked extremely well – identifying over
99% of characters correctly based on grammatical and
statistical constraints.
Dynamic programming (the Viterbi algorithm) can be used
on the sentences to obtain the same results, by finding the
shortest paths in the underlying DAG.
Shortest Paths: Unweighted Graphs
In an unweighted graph, the cost of a path is just the number
of edges on the shortest path, which can be found in O(n+m)
time via breadth-first search.
In a weighted graph, the weight of a path between two
vertices is the sum of the weights of the edges on a path.
BFS will not work on weighted graphs because sometimes
visiting more edges can lead to shorter distance, ie.
1 + 1 + 1 + 1 + 1 + 1 + 1  10.
Note that there can be an exponential number of shortest paths
between two nodes – so we cannot report all shortest paths
efficiently.
Negative Edge Weights
Note that negative cost cycles render the problem of finding
the shortest path meaningless, since you can always loop
around the negative cost cycle more to reduce the cost of the
path.
Thus in our discussions, we will assume that all edge weights
are positive. Other algorithms deal correctly with negative
cost edges.
Minimum spanning trees are uneffected by negative cost
edges.
Dijkstra’s Algorithm
The principle behind Dijkstra’s algorithm is that if
s, . . . , x, . . . , t is the shortest path from s to t, then s, . . . , x
had better be the shortest path from s to x.
This suggests a dynamic programming-like strategy, where
we store the distance from s to all nearby nodes, and use them
to find the shortest path to more distant nodes.
Initialization and Update
The shortest path from s to s, d(s, s) = 0. If all edge weights
are positive, the smallest edge incident to s, say (s, x), defines
d(s, x).
We can use an array to store the length of the shortest path to
each node. Initialize each to ∞ to start.
Soon as we establish the shortest path from s to a new node
x, we go through each of its incident edges to see if there is a
better way from s to other nodes thru x.
Pseudocode: Dijkstra’s Algorithm
known = {s}
for i = 1 to n, dist[i] = ∞
for each edge (s, v), dist[v] = d(s, v)
last=s
while (last = t)
       select v such that dist(v) = minunknown dist(i)
       for each (v, x), dist[x] = min(dist[x], dist[v] + w(v, x))
       last=v
       known = known ∪ {v}

Complexity → O(n2 ).
This is essentially the same as Prim’s algorithm.
Dijkstra Example

                               5
          7
                           2           2                           6
                       4                                5
              9            3                                   3

      5       7            4       7       1    2              4

      A           12                       A

                  G                            Dijkstra(G,A)
Dijkstra’s Implementation
See how little changes from Prim’s algorithm!
dijkstra(graph *g, int start) (* WAS prim(g,start) *)
{
      int i; (* counter *)
      edgenode *p; (* temporary pointer *)
      bool intree[MAXV]; (* is the vertex in the tree yet? *)
      int distance[MAXV]; (* distance vertex is from start *)
      int v; (* current vertex to process *)
      int w; (* candidate next vertex *)
      int weight; (* edge weight *)
      int dist; (* best current distance from start *)

      for (i=1; i=g− nvertices; i++) {
             intree[i] = FALSE;
             distance[i] = MAXINT;
             parent[i] = -1;
      }

      distance[start] = 0;
      v = start;
while (intree[v] == FALSE) {
           intree[v] = TRUE;
           p = g− edges[v];
           while (p ! = NULL) {
                  w = p− y;
                  weight = p− weight;
(* CHANGED *) if (distance[w]  (distance[v]+weight)) {
(* CHANGED *)           distance[w] = distance[v]+weight;
(* CHANGED *)           parent[w] = v;
                  }
                  p = p− next;
           }

           v = 1;
           dist = MAXINT;
           for (i=1; i= g− nvertices; i++)
                  if ((intree[i] == FALSE)  (dist  distance[i])) {
                          dist = distance[i];
                          v = i;
                  }
     }
}
Prim’s/Dijkstra’s Analysis
Finding the minimum weight fringe-edge takes O(n) time –
just bump through fringe list.
After adding a vertex to the tree, running through its
adjacency list to update the cost of adding fringe vertices
(there may be a cheaper way through the new vertex) can be
done in O(n) time.
Total time is O(n2 ).
Improved Time Bounds
An O(m lg n) implementation of Dijkstra’s algorithm would
be faster for sparse graphs, and comes from using a heap of
the vertices (ordered by distance), and updating the distance
to each vertex (if necessary) in O(lg n) time for each edge out
from freshly known vertices.
Even better, O(n lg n + m) follows from using Fibonacci
heaps, since they permit one to do a decrease-key operation
in O(1) amortized time.
All-Pairs Shortest Path
Notice that finding the shortest path between a pair of vertices
(s, t) in worst case requires first finding the shortest path from
s to all other vertices in the graph.
Many applications, such as finding the center or diameter of
a graph, require finding the shortest path between all pairs of
vertices.
We can run Dijkstra’s algorithm n times (once from each
possible start vertex) to solve all-pairs shortest path problem
in O(n3 ). Can we do better?
Dynamic Programming and Shortest Paths
The four-step approach to dynamic programming is:
1. Characterize the structure of an optimal solution.
2. Recursively define the value of an optimal solution.
3. Compute this recurrence in a bottom-up fashion.
4. Extract the optimal solution from computed information.
Initialization
From the adjacency matrix, we can construct the following
matrix:
D[i, j] = ∞,       if i = j and (vi , vj ) is not in E
D[i, j] = w(i, j), if (vi, vj ) ∈ E
D[i, j] = 0,       if i = j
This tells us the shortest path going through no intermediate
nodes.
Characterization Based on Path Length
There are several ways to characterize the shortest path
between two nodes in a graph. Note that the shortest path
from i to j, i = j, using at most M edges consists of the
shortest path from i to k using at most M − 1 edges+W (k, j)
for some k.
This suggests that we can compute all-pair shortest path with
an induction based on the number of edges in the optimal
path.
Recurrence on Path Length
Let d[i, j]m be the length of the shortest path from i to j using
at most m edges.
What is d[i, j]0?
                     d[i, j]0 = 0 if i = j
                              = ∞ if i = j
What if we know d[i, j]m−1 for all i, j?
    d[i, j]m = min(d[i, j]m−1 , min(d[i, k]m−1 + w[k, j]))
             = min(d[i, k]m−1 + w[k, j]), 1 ≤ k ≤ i
since w[k, k] = 0
Not Floyd Implementation
This gives us a recurrence, which we can evaluate in a bottom
up fashion:
for i = 1 to n
       for j = 1 to n
       d[i, j]m = ∞
       for k = 1 to n
              d[i, j]0 =Min( d[i, k]m , d[i, k]m−1 + d[k, j])
Time Analysis – Bummer

This is an O(n3 ) algorithm just like matrix multiplication, but
it only goes from m to m + 1 edges.
Since the shortest path between any two nodes must use at
most n edges (unless we have negative cost cycles), we must
repeat that procedure n times (m = 1 to n) for an O(n4 )
algorithm.
Although this is slick, observe that even O(n3 log n) is
slower than running Dijkstra’s algorithm starting from each
vertex!
The Floyd-Warshall Algorithm
An alternate recurrence yields a more efficient dynamic
programming formulation. Number the vertices from 1 to n.
Let d[i, j]k be the shortest path from i to j using only vertices
from 1, 2, ..., k as possible intermediate vertices.
What is d[j, j]0 ? With no intermediate vertices, any path
consists of at most one edge, so d[i, j]0 = w[i, j].
Recurrence Relation
In general, adding a new vertex k + 1 helps iff a path goes
through it, so

  d[i, j]k = w[i, j] if k = 0
           = min(d[i, j]k−1 , d[i, k]k−1 + d[k, j]k−1 ) if k ≥ 1
Although this looks similar to the previous recurrence, it isn’t.
Implementation
The following algorithm implements it:
do = w
for k = 1 to n
      for i = 1 to n
             for j = 1 to n
             d[i, j]k = min(d[i, j]k−1 , d[i, k]k−1 + d[k, j]k−1 )


This obviously runs in Θ(n3 ) time, which is asymptotically
no better than n calls to Dijkstra’s algorithm.
However, the loops are so tight and it is so short and simple
that it runs better in practice by a constant factor.

More Related Content

What's hot

Temp terms1 2-09
Temp terms1 2-09Temp terms1 2-09
Temp terms1 2-09fisherysim
 
Talk given in at the Joint Research Centre, Ispra, Italy, December 2009.
Talk given in at the Joint Research Centre, Ispra, Italy, December 2009.Talk given in at the Joint Research Centre, Ispra, Italy, December 2009.
Talk given in at the Joint Research Centre, Ispra, Italy, December 2009.larry77
 
08 relations-x4
08 relations-x408 relations-x4
08 relations-x4J00MZ
 
מדיניות עירונית ומהגרי עבודה
מדיניות עירונית ומהגרי עבודהמדיניות עירונית ומהגרי עבודה
מדיניות עירונית ומהגרי עבודהJonathan Heyman
 
Lecture5 Normalization
Lecture5 NormalizationLecture5 Normalization
Lecture5 Normalizationguest800d4
 
קיבוץ ניר יצחק
 קיבוץ ניר יצחק קיבוץ ניר יצחק
קיבוץ ניר יצחקnir yitzhak
 
Motorcycle Recall PDF
Motorcycle Recall PDFMotorcycle Recall PDF
Motorcycle Recall PDFAnapol Weiss
 
Tobacco Cigarettes
Tobacco CigarettesTobacco Cigarettes
Tobacco Cigaretteszakir2012
 
Wives Rather Than Mistresses
Wives Rather Than MistressesWives Rather Than Mistresses
Wives Rather Than Mistresseszakir2012
 
ApresentaçãO 3 Q09 Cr2
ApresentaçãO 3 Q09   Cr2ApresentaçãO 3 Q09   Cr2
ApresentaçãO 3 Q09 Cr2CR2
 
ESS-Bilbao Initiative Workshop.Review of SC spokes cavities for low-medium en...
ESS-Bilbao Initiative Workshop.Review of SC spokes cavities for low-medium en...ESS-Bilbao Initiative Workshop.Review of SC spokes cavities for low-medium en...
ESS-Bilbao Initiative Workshop.Review of SC spokes cavities for low-medium en...ESS BILBAO
 
Position paper cars august 11, 2011
Position paper cars august 11, 2011Position paper cars august 11, 2011
Position paper cars august 11, 2011Anochi.com.
 

What's hot (18)

Temp terms1 2-09
Temp terms1 2-09Temp terms1 2-09
Temp terms1 2-09
 
Metodologia
MetodologiaMetodologia
Metodologia
 
Talk given in at the Joint Research Centre, Ispra, Italy, December 2009.
Talk given in at the Joint Research Centre, Ispra, Italy, December 2009.Talk given in at the Joint Research Centre, Ispra, Italy, December 2009.
Talk given in at the Joint Research Centre, Ispra, Italy, December 2009.
 
08 relations-x4
08 relations-x408 relations-x4
08 relations-x4
 
Quranic therapy booklet 2
Quranic therapy booklet 2Quranic therapy booklet 2
Quranic therapy booklet 2
 
מדיניות עירונית ומהגרי עבודה
מדיניות עירונית ומהגרי עבודהמדיניות עירונית ומהגרי עבודה
מדיניות עירונית ומהגרי עבודה
 
Akerman nachliel-hifchi
Akerman nachliel-hifchiAkerman nachliel-hifchi
Akerman nachliel-hifchi
 
Lecture5 Normalization
Lecture5 NormalizationLecture5 Normalization
Lecture5 Normalization
 
קיבוץ ניר יצחק
 קיבוץ ניר יצחק קיבוץ ניר יצחק
קיבוץ ניר יצחק
 
Motorcycle Recall PDF
Motorcycle Recall PDFMotorcycle Recall PDF
Motorcycle Recall PDF
 
Como mentir con estadísticas
Como mentir con estadísticasComo mentir con estadísticas
Como mentir con estadísticas
 
Tobacco Cigarettes
Tobacco CigarettesTobacco Cigarettes
Tobacco Cigarettes
 
Wives Rather Than Mistresses
Wives Rather Than MistressesWives Rather Than Mistresses
Wives Rather Than Mistresses
 
ApresentaçãO 3 Q09 Cr2
ApresentaçãO 3 Q09   Cr2ApresentaçãO 3 Q09   Cr2
ApresentaçãO 3 Q09 Cr2
 
פניה למינהל ולשר השיכון 24.12.09
פניה למינהל ולשר השיכון 24.12.09פניה למינהל ולשר השיכון 24.12.09
פניה למינהל ולשר השיכון 24.12.09
 
ESS-Bilbao Initiative Workshop.Review of SC spokes cavities for low-medium en...
ESS-Bilbao Initiative Workshop.Review of SC spokes cavities for low-medium en...ESS-Bilbao Initiative Workshop.Review of SC spokes cavities for low-medium en...
ESS-Bilbao Initiative Workshop.Review of SC spokes cavities for low-medium en...
 
Position paper cars august 11, 2011
Position paper cars august 11, 2011Position paper cars august 11, 2011
Position paper cars august 11, 2011
 
361o 1 semana_9
361o 1 semana_9361o 1 semana_9
361o 1 semana_9
 

Viewers also liked

DESIGN AND IMPLEMENTATION OF PATH PLANNING ALGORITHM
DESIGN AND IMPLEMENTATION OF PATH PLANNING ALGORITHM DESIGN AND IMPLEMENTATION OF PATH PLANNING ALGORITHM
DESIGN AND IMPLEMENTATION OF PATH PLANNING ALGORITHM NITISH K
 
All pair shortest path--SDN
All pair shortest path--SDNAll pair shortest path--SDN
All pair shortest path--SDNSarat Prasad
 
Dijkstra algorithm
Dijkstra algorithmDijkstra algorithm
Dijkstra algorithmare you
 
All Pair Shortest Path Algorithm – Parallel Implementation and Analysis
All Pair Shortest Path Algorithm – Parallel Implementation and AnalysisAll Pair Shortest Path Algorithm – Parallel Implementation and Analysis
All Pair Shortest Path Algorithm – Parallel Implementation and AnalysisInderjeet Singh
 
Dijkstra’s algorithm
Dijkstra’s algorithmDijkstra’s algorithm
Dijkstra’s algorithmfaisal2204
 
Dijkstra’S Algorithm
Dijkstra’S AlgorithmDijkstra’S Algorithm
Dijkstra’S Algorithmami_01
 

Viewers also liked (11)

DIGITAL TEXT BOOK
DIGITAL TEXT BOOKDIGITAL TEXT BOOK
DIGITAL TEXT BOOK
 
Assignment 2
Assignment 2Assignment 2
Assignment 2
 
DESIGN AND IMPLEMENTATION OF PATH PLANNING ALGORITHM
DESIGN AND IMPLEMENTATION OF PATH PLANNING ALGORITHM DESIGN AND IMPLEMENTATION OF PATH PLANNING ALGORITHM
DESIGN AND IMPLEMENTATION OF PATH PLANNING ALGORITHM
 
All pair shortest path--SDN
All pair shortest path--SDNAll pair shortest path--SDN
All pair shortest path--SDN
 
Dijksatra
DijksatraDijksatra
Dijksatra
 
Dijkstra algorithm
Dijkstra algorithmDijkstra algorithm
Dijkstra algorithm
 
ASSIGNMENT 1
ASSIGNMENT 1ASSIGNMENT 1
ASSIGNMENT 1
 
All Pair Shortest Path Algorithm – Parallel Implementation and Analysis
All Pair Shortest Path Algorithm – Parallel Implementation and AnalysisAll Pair Shortest Path Algorithm – Parallel Implementation and Analysis
All Pair Shortest Path Algorithm – Parallel Implementation and Analysis
 
Dijkstra’s algorithm
Dijkstra’s algorithmDijkstra’s algorithm
Dijkstra’s algorithm
 
Dijkstra’S Algorithm
Dijkstra’S AlgorithmDijkstra’S Algorithm
Dijkstra’S Algorithm
 
Shortest Path Problem
Shortest Path ProblemShortest Path Problem
Shortest Path Problem
 

Similar to Skiena algorithm 2007 lecture14 shortest path

ESS-Bilbao Initiative Workshop. Spokes vs. Elliptical cavities for medium-hig...
ESS-Bilbao Initiative Workshop. Spokes vs. Elliptical cavities for medium-hig...ESS-Bilbao Initiative Workshop. Spokes vs. Elliptical cavities for medium-hig...
ESS-Bilbao Initiative Workshop. Spokes vs. Elliptical cavities for medium-hig...ESS BILBAO
 
A Good Library And Librarian Are Crucial For Faculty Growth
A Good Library And Librarian Are Crucial For Faculty GrowthA Good Library And Librarian Are Crucial For Faculty Growth
A Good Library And Librarian Are Crucial For Faculty GrowthAnil Mishra
 
Biofuel For Transport in Sweden
Biofuel For Transport in SwedenBiofuel For Transport in Sweden
Biofuel For Transport in SwedenLenaDahlman
 
Pictures of success
Pictures of successPictures of success
Pictures of successjasonng
 
ESS-Bilbao Initiative Workshop. R&D Towards mitigation of cavitation damage i...
ESS-Bilbao Initiative Workshop. R&D Towards mitigation of cavitation damage i...ESS-Bilbao Initiative Workshop. R&D Towards mitigation of cavitation damage i...
ESS-Bilbao Initiative Workshop. R&D Towards mitigation of cavitation damage i...ESS BILBAO
 
分光光度法快速测定玉米叶片中的叶绿素
分光光度法快速测定玉米叶片中的叶绿素分光光度法快速测定玉米叶片中的叶绿素
分光光度法快速测定玉米叶片中的叶绿素sugeladi
 
Manual buenas practicas
Manual buenas practicasManual buenas practicas
Manual buenas practicasVLADIMIR LTDA
 
[x+1] Company Overview
[x+1] Company Overview[x+1] Company Overview
[x+1] Company Overview[x+1]
 
bctntlvn (108).pdf
bctntlvn (108).pdfbctntlvn (108).pdf
bctntlvn (108).pdfLuanvan84
 
les petites villes surprennent :Dossier baromètre des villes marocaines 2011 ...
les petites villes surprennent :Dossier baromètre des villes marocaines 2011 ...les petites villes surprennent :Dossier baromètre des villes marocaines 2011 ...
les petites villes surprennent :Dossier baromètre des villes marocaines 2011 ...Tizart Lab
 
台北吃喝玩樂四天自遊團 18 mar
台北吃喝玩樂四天自遊團 18 mar台北吃喝玩樂四天自遊團 18 mar
台北吃喝玩樂四天自遊團 18 marAlice Tang
 
Techila Azure Use Cases
Techila Azure Use CasesTechila Azure Use Cases
Techila Azure Use CasesLee Stott
 
Best of dynami In Atlanta (2)
Best of dynami In Atlanta (2)Best of dynami In Atlanta (2)
Best of dynami In Atlanta (2)Liza Doyle
 

Similar to Skiena algorithm 2007 lecture14 shortest path (20)

Nano-IV(2005) Kanda et.al
Nano-IV(2005) Kanda et.alNano-IV(2005) Kanda et.al
Nano-IV(2005) Kanda et.al
 
Revista Española de Defensa
Revista Española de DefensaRevista Española de Defensa
Revista Española de Defensa
 
ESS-Bilbao Initiative Workshop. Spokes vs. Elliptical cavities for medium-hig...
ESS-Bilbao Initiative Workshop. Spokes vs. Elliptical cavities for medium-hig...ESS-Bilbao Initiative Workshop. Spokes vs. Elliptical cavities for medium-hig...
ESS-Bilbao Initiative Workshop. Spokes vs. Elliptical cavities for medium-hig...
 
A Good Library And Librarian Are Crucial For Faculty Growth
A Good Library And Librarian Are Crucial For Faculty GrowthA Good Library And Librarian Are Crucial For Faculty Growth
A Good Library And Librarian Are Crucial For Faculty Growth
 
Biofuel For Transport in Sweden
Biofuel For Transport in SwedenBiofuel For Transport in Sweden
Biofuel For Transport in Sweden
 
Pictures of success
Pictures of successPictures of success
Pictures of success
 
ESS-Bilbao Initiative Workshop. R&D Towards mitigation of cavitation damage i...
ESS-Bilbao Initiative Workshop. R&D Towards mitigation of cavitation damage i...ESS-Bilbao Initiative Workshop. R&D Towards mitigation of cavitation damage i...
ESS-Bilbao Initiative Workshop. R&D Towards mitigation of cavitation damage i...
 
分光光度法快速测定玉米叶片中的叶绿素
分光光度法快速测定玉米叶片中的叶绿素分光光度法快速测定玉米叶片中的叶绿素
分光光度法快速测定玉米叶片中的叶绿素
 
1 la candeur
1 la candeur1 la candeur
1 la candeur
 
Manual buenas practicas
Manual buenas practicasManual buenas practicas
Manual buenas practicas
 
[x+1] Company Overview
[x+1] Company Overview[x+1] Company Overview
[x+1] Company Overview
 
bctntlvn (108).pdf
bctntlvn (108).pdfbctntlvn (108).pdf
bctntlvn (108).pdf
 
les petites villes surprennent :Dossier baromètre des villes marocaines 2011 ...
les petites villes surprennent :Dossier baromètre des villes marocaines 2011 ...les petites villes surprennent :Dossier baromètre des villes marocaines 2011 ...
les petites villes surprennent :Dossier baromètre des villes marocaines 2011 ...
 
Cs gate-2012
Cs gate-2012Cs gate-2012
Cs gate-2012
 
Solutions4SME
Solutions4SMESolutions4SME
Solutions4SME
 
台北吃喝玩樂四天自遊團 18 mar
台北吃喝玩樂四天自遊團 18 mar台北吃喝玩樂四天自遊團 18 mar
台北吃喝玩樂四天自遊團 18 mar
 
Hotmail
HotmailHotmail
Hotmail
 
Betagov content testing 13.1.2012 final
Betagov content testing 13.1.2012 finalBetagov content testing 13.1.2012 final
Betagov content testing 13.1.2012 final
 
Techila Azure Use Cases
Techila Azure Use CasesTechila Azure Use Cases
Techila Azure Use Cases
 
Best of dynami In Atlanta (2)
Best of dynami In Atlanta (2)Best of dynami In Atlanta (2)
Best of dynami In Atlanta (2)
 

More from zukun

My lyn tutorial 2009
My lyn tutorial 2009My lyn tutorial 2009
My lyn tutorial 2009zukun
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVzukun
 
ETHZ CV2012: Information
ETHZ CV2012: InformationETHZ CV2012: Information
ETHZ CV2012: Informationzukun
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statisticsSiwei lyu: natural image statistics
Siwei lyu: natural image statisticszukun
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibrationzukun
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionBrunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionzukun
 
Modern features-part-4-evaluation
Modern features-part-4-evaluationModern features-part-4-evaluation
Modern features-part-4-evaluationzukun
 
Modern features-part-3-software
Modern features-part-3-softwareModern features-part-3-software
Modern features-part-3-softwarezukun
 
Modern features-part-2-descriptors
Modern features-part-2-descriptorsModern features-part-2-descriptors
Modern features-part-2-descriptorszukun
 
Modern features-part-1-detectors
Modern features-part-1-detectorsModern features-part-1-detectors
Modern features-part-1-detectorszukun
 
Modern features-part-0-intro
Modern features-part-0-introModern features-part-0-intro
Modern features-part-0-introzukun
 
Lecture 02 internet video search
Lecture 02 internet video searchLecture 02 internet video search
Lecture 02 internet video searchzukun
 
Lecture 01 internet video search
Lecture 01 internet video searchLecture 01 internet video search
Lecture 01 internet video searchzukun
 
Lecture 03 internet video search
Lecture 03 internet video searchLecture 03 internet video search
Lecture 03 internet video searchzukun
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learningIcml2012 tutorial representation_learning
Icml2012 tutorial representation_learningzukun
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionAdvances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionzukun
 
Gephi tutorial: quick start
Gephi tutorial: quick startGephi tutorial: quick start
Gephi tutorial: quick startzukun
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysisEM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysiszukun
 
Object recognition with pictorial structures
Object recognition with pictorial structuresObject recognition with pictorial structures
Object recognition with pictorial structureszukun
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities zukun
 

More from zukun (20)

My lyn tutorial 2009
My lyn tutorial 2009My lyn tutorial 2009
My lyn tutorial 2009
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCV
 
ETHZ CV2012: Information
ETHZ CV2012: InformationETHZ CV2012: Information
ETHZ CV2012: Information
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statisticsSiwei lyu: natural image statistics
Siwei lyu: natural image statistics
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibration
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionBrunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer vision
 
Modern features-part-4-evaluation
Modern features-part-4-evaluationModern features-part-4-evaluation
Modern features-part-4-evaluation
 
Modern features-part-3-software
Modern features-part-3-softwareModern features-part-3-software
Modern features-part-3-software
 
Modern features-part-2-descriptors
Modern features-part-2-descriptorsModern features-part-2-descriptors
Modern features-part-2-descriptors
 
Modern features-part-1-detectors
Modern features-part-1-detectorsModern features-part-1-detectors
Modern features-part-1-detectors
 
Modern features-part-0-intro
Modern features-part-0-introModern features-part-0-intro
Modern features-part-0-intro
 
Lecture 02 internet video search
Lecture 02 internet video searchLecture 02 internet video search
Lecture 02 internet video search
 
Lecture 01 internet video search
Lecture 01 internet video searchLecture 01 internet video search
Lecture 01 internet video search
 
Lecture 03 internet video search
Lecture 03 internet video searchLecture 03 internet video search
Lecture 03 internet video search
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learningIcml2012 tutorial representation_learning
Icml2012 tutorial representation_learning
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionAdvances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer vision
 
Gephi tutorial: quick start
Gephi tutorial: quick startGephi tutorial: quick start
Gephi tutorial: quick start
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysisEM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysis
 
Object recognition with pictorial structures
Object recognition with pictorial structuresObject recognition with pictorial structures
Object recognition with pictorial structures
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Skiena algorithm 2007 lecture14 shortest path

  • 1. Lecture 14: Shortest Paths Steven Skiena Department of Computer Science State University of New York Stony Brook, NY 11794–4400 http://www.cs.sunysb.edu/∼skiena
  • 2. Problem of the Day Suppose we are given the minimum spanning tree T of a given graph G (with n vertices and m edges) and a new edge e = (u, v) of weight w that we will add to G. Give an efficient algorithm to find the minimum spanning tree of the graph G + e. Your algorithm should run in O(n) time to receive full credit, although slower but correct algorithms will receive partial credit.
  • 3. Shortest Paths Finding the shortest path between two nodes in a graph arises in many different applications: • Transportation problems – finding the cheapest way to travel between two locations. • Motion planning – what is the most natural way for a cartoon character to move about a simulated environment. • Communications problems – how look will it take for a message to get between two places? Which two locations are furthest apart, ie. what is the diameter of the network.
  • 4. Shortest Paths and Sentence Disambiguation In our work on reconstructing text typed on an (overloaded) telephone keypad, we had to select which of many possible interpretations was most likely. We constructed a graph where the vertices were the possible words/positions in the sentence, with an edge between possible neighboring words.
  • 5. r ` q a h g d e d b a s£©pif2f2c£` ¡ y x ¡ y C™2C¥n # $ 5 %6 8 $ u 5 %6 7 pt t ' 21 u $ % 56 54 t 3 w pv v v 0) pt t t ' & % ( ' % $ ’ “” „ g “ l k „ “ i ‰ …‰” …‰ £… •€£€’ 2m™•e UjYC•2™h $ 5 %6 8 # $ 5 %6 7 ' 21 ' % ( $ % 56 54 3 0) ' % $ # # # #                 ! ! ! ¨¦ ¤ ¢ §¥£¡ ¨ ¦ ¤ ¢ ©§¥£¡ ¨ ¦ ¤ ¢ ©£¥£¡ ¨ ¦ ¤ ¢ ©§¥£¡ … “” gf”e … ‘ – ‰” „ “ ˜ … „ €‘ •Y£•55£€—d•™C˜ 2£€—–         #         ! ! ! ¨¦ ¤ ¢ §¥£¡ ¨ ¦ ¤ ¢ ©§¥£¡ ¨ ¦ ¤ ¢ ©£¥£¡ ¨ ¦ ¤ ¢ ©§¥£¡ …€‘ “•” “C…€’€YYUˆC€„ ƒ ‘‰ ‡ † … ‚ # 999 B D R D T Q S Q I R Q I G D D B 99 @YXWVHUPPFPPFPPHFECA@9 ¡ y x q C€2ca
  • 6. Weighting the Graph Code C 1 Code C 2 Code C 3 1 P(W1/C 1) 2 P(W1/C 2) P(W13 3) /C 4 P(#/W 1) P(W11/#) 1 2 1 P(W2/W1) 3 P(W2/C 1) P(W2/C 3) P(W21/#) # P(W22 2) /C # P(W31/#) 1 P(W3/C 1) P(W33 3) /C P(W41/#) P(W41 1) /C P(W43 3) /C The weight of each edge is a function of the probability that these two words will be next to each other in a sentence. ‘hive me’ would be less than ‘give me’, for example. The final system worked extremely well – identifying over 99% of characters correctly based on grammatical and statistical constraints.
  • 7. Dynamic programming (the Viterbi algorithm) can be used on the sentences to obtain the same results, by finding the shortest paths in the underlying DAG.
  • 8. Shortest Paths: Unweighted Graphs In an unweighted graph, the cost of a path is just the number of edges on the shortest path, which can be found in O(n+m) time via breadth-first search. In a weighted graph, the weight of a path between two vertices is the sum of the weights of the edges on a path. BFS will not work on weighted graphs because sometimes visiting more edges can lead to shorter distance, ie. 1 + 1 + 1 + 1 + 1 + 1 + 1 10. Note that there can be an exponential number of shortest paths between two nodes – so we cannot report all shortest paths efficiently.
  • 9. Negative Edge Weights Note that negative cost cycles render the problem of finding the shortest path meaningless, since you can always loop around the negative cost cycle more to reduce the cost of the path. Thus in our discussions, we will assume that all edge weights are positive. Other algorithms deal correctly with negative cost edges. Minimum spanning trees are uneffected by negative cost edges.
  • 10. Dijkstra’s Algorithm The principle behind Dijkstra’s algorithm is that if s, . . . , x, . . . , t is the shortest path from s to t, then s, . . . , x had better be the shortest path from s to x. This suggests a dynamic programming-like strategy, where we store the distance from s to all nearby nodes, and use them to find the shortest path to more distant nodes.
  • 11. Initialization and Update The shortest path from s to s, d(s, s) = 0. If all edge weights are positive, the smallest edge incident to s, say (s, x), defines d(s, x). We can use an array to store the length of the shortest path to each node. Initialize each to ∞ to start. Soon as we establish the shortest path from s to a new node x, we go through each of its incident edges to see if there is a better way from s to other nodes thru x.
  • 12. Pseudocode: Dijkstra’s Algorithm known = {s} for i = 1 to n, dist[i] = ∞ for each edge (s, v), dist[v] = d(s, v) last=s while (last = t) select v such that dist(v) = minunknown dist(i) for each (v, x), dist[x] = min(dist[x], dist[v] + w(v, x)) last=v known = known ∪ {v} Complexity → O(n2 ). This is essentially the same as Prim’s algorithm.
  • 13. Dijkstra Example 5 7 2 2 6 4 5 9 3 3 5 7 4 7 1 2 4 A 12 A G Dijkstra(G,A)
  • 14. Dijkstra’s Implementation See how little changes from Prim’s algorithm! dijkstra(graph *g, int start) (* WAS prim(g,start) *) { int i; (* counter *) edgenode *p; (* temporary pointer *) bool intree[MAXV]; (* is the vertex in the tree yet? *) int distance[MAXV]; (* distance vertex is from start *) int v; (* current vertex to process *) int w; (* candidate next vertex *) int weight; (* edge weight *) int dist; (* best current distance from start *) for (i=1; i=g− nvertices; i++) { intree[i] = FALSE; distance[i] = MAXINT; parent[i] = -1; } distance[start] = 0; v = start;
  • 15. while (intree[v] == FALSE) { intree[v] = TRUE; p = g− edges[v]; while (p ! = NULL) { w = p− y; weight = p− weight; (* CHANGED *) if (distance[w] (distance[v]+weight)) { (* CHANGED *) distance[w] = distance[v]+weight; (* CHANGED *) parent[w] = v; } p = p− next; } v = 1; dist = MAXINT; for (i=1; i= g− nvertices; i++) if ((intree[i] == FALSE) (dist distance[i])) { dist = distance[i]; v = i; } } }
  • 16. Prim’s/Dijkstra’s Analysis Finding the minimum weight fringe-edge takes O(n) time – just bump through fringe list. After adding a vertex to the tree, running through its adjacency list to update the cost of adding fringe vertices (there may be a cheaper way through the new vertex) can be done in O(n) time. Total time is O(n2 ).
  • 17. Improved Time Bounds An O(m lg n) implementation of Dijkstra’s algorithm would be faster for sparse graphs, and comes from using a heap of the vertices (ordered by distance), and updating the distance to each vertex (if necessary) in O(lg n) time for each edge out from freshly known vertices. Even better, O(n lg n + m) follows from using Fibonacci heaps, since they permit one to do a decrease-key operation in O(1) amortized time.
  • 18. All-Pairs Shortest Path Notice that finding the shortest path between a pair of vertices (s, t) in worst case requires first finding the shortest path from s to all other vertices in the graph. Many applications, such as finding the center or diameter of a graph, require finding the shortest path between all pairs of vertices. We can run Dijkstra’s algorithm n times (once from each possible start vertex) to solve all-pairs shortest path problem in O(n3 ). Can we do better?
  • 19. Dynamic Programming and Shortest Paths The four-step approach to dynamic programming is: 1. Characterize the structure of an optimal solution. 2. Recursively define the value of an optimal solution. 3. Compute this recurrence in a bottom-up fashion. 4. Extract the optimal solution from computed information.
  • 20. Initialization From the adjacency matrix, we can construct the following matrix: D[i, j] = ∞, if i = j and (vi , vj ) is not in E D[i, j] = w(i, j), if (vi, vj ) ∈ E D[i, j] = 0, if i = j This tells us the shortest path going through no intermediate nodes.
  • 21. Characterization Based on Path Length There are several ways to characterize the shortest path between two nodes in a graph. Note that the shortest path from i to j, i = j, using at most M edges consists of the shortest path from i to k using at most M − 1 edges+W (k, j) for some k. This suggests that we can compute all-pair shortest path with an induction based on the number of edges in the optimal path.
  • 22. Recurrence on Path Length Let d[i, j]m be the length of the shortest path from i to j using at most m edges. What is d[i, j]0? d[i, j]0 = 0 if i = j = ∞ if i = j What if we know d[i, j]m−1 for all i, j? d[i, j]m = min(d[i, j]m−1 , min(d[i, k]m−1 + w[k, j])) = min(d[i, k]m−1 + w[k, j]), 1 ≤ k ≤ i since w[k, k] = 0
  • 23. Not Floyd Implementation This gives us a recurrence, which we can evaluate in a bottom up fashion: for i = 1 to n for j = 1 to n d[i, j]m = ∞ for k = 1 to n d[i, j]0 =Min( d[i, k]m , d[i, k]m−1 + d[k, j])
  • 24. Time Analysis – Bummer This is an O(n3 ) algorithm just like matrix multiplication, but it only goes from m to m + 1 edges. Since the shortest path between any two nodes must use at most n edges (unless we have negative cost cycles), we must repeat that procedure n times (m = 1 to n) for an O(n4 ) algorithm. Although this is slick, observe that even O(n3 log n) is slower than running Dijkstra’s algorithm starting from each vertex!
  • 25. The Floyd-Warshall Algorithm An alternate recurrence yields a more efficient dynamic programming formulation. Number the vertices from 1 to n. Let d[i, j]k be the shortest path from i to j using only vertices from 1, 2, ..., k as possible intermediate vertices. What is d[j, j]0 ? With no intermediate vertices, any path consists of at most one edge, so d[i, j]0 = w[i, j].
  • 26. Recurrence Relation In general, adding a new vertex k + 1 helps iff a path goes through it, so d[i, j]k = w[i, j] if k = 0 = min(d[i, j]k−1 , d[i, k]k−1 + d[k, j]k−1 ) if k ≥ 1 Although this looks similar to the previous recurrence, it isn’t.
  • 27. Implementation The following algorithm implements it: do = w for k = 1 to n for i = 1 to n for j = 1 to n d[i, j]k = min(d[i, j]k−1 , d[i, k]k−1 + d[k, j]k−1 ) This obviously runs in Θ(n3 ) time, which is asymptotically no better than n calls to Dijkstra’s algorithm. However, the loops are so tight and it is so short and simple that it runs better in practice by a constant factor.