SlideShare uma empresa Scribd logo
1 de 28
Data Structures and Algorithms


              Graphs
  Single-Source Shortest Paths
      (Dijkstra’s Algorithm)
           PLSD210(ii)
Graphs - Shortest Paths
• Application
  • In a graph in which edges have costs ..
  • Find the shortest path from a source to a destination
  • Surprisingly ..
      • While finding the shortest path from a source to one
        destination,
      • we can find the shortest paths to all over
        destinations as well!
  • Common algorithm for
          single-source shortest paths
    is due to Edsger Dijkstra
Dijkstra’s Algorithm - Data Structures
• For a graph,
                   G = ( V, E )
• Dijkstra’s algorithm keeps two sets of vertices:
      S     Vertices whose shortest paths have already been
             determined
     V-S     Remainder
• Also
     d       Best estimates of shortest path to each vertex
     π       Predecessors for each vertex
Predecessor Sub-graph
• Array of vertex indices, π[j], j = 1 .. |V|
   •   π[j] contains the pre-decessor for node j
   •   j’s predecessor is in π[π[j]], and so on ....
   •   The edges in the pre-decessor sub-graph are
                   ( π[j], j )
Dijkstra’s Algorithm - Operation
• Initialise d and π
   • For each vertex, j, in V
       • dj = ∞                 Initial estimates are all ∞

       • π j = nil              No connections

   • Source distance, ds = 0
• Set S to empty
• While V-S is not empty
   • Sort V-S based on d
                                                     Add s first!
   • Add u, the closest vertex in V-S, to S
   • Relax all the vertices still in V-S connected to u
Dijkstra’s Algorithm - Operation
• Initialise d and π
   • For each vertex, j, in V
       • dj = ∞
       • π j = nil               Initial estimates are all ∞
                                No connections
   • Source distance, ds = 0
• Set S to empty
• While V-S is not empty
   • Sort V-S based on d
   • Add u, the closest vertex in V-S, to S
                                                     Add s first!
   • Relax all the vertices still in V-S connected to u
Dijkstra’s Algorithm - Operation
• The Relaxation process

Relax the node v
attached to node u   Edge cost matrix

                                        If the current best
relax( Node u, Node v, double w[][] )
                                        estimate to v is
    if d[v] > d[u] + w[u,v] then
                                        greater than the
        d[v] := d[u] + w[u,v]
                                        path through u ..
        pi[v] := u
                       Update the
 Make v’s predecessor estimate to v
      point to u
Dijkstra’s Algorithm - Full
  • The Shortest Paths algorithm

Given a graph, g, and a source, s

shortest_paths( Graph g, Node s )
    initialise_single_source( g, s )
    S := { 0 }         /* Make S empty */
    Q := Vertices( g ) /* Put the vertices in a PQ */
    while not Empty(Q)
        u := ExtractCheapest( Q );
        AddNode( S, u ); /* Add u to S */
        for each vertex v in Adjacent( u )
            relax( u, v, w )
Dijkstra’s Algorithm - Initialise
  • The Shortest Paths algorithm
Given a graph, g,
                                   Initialise d, π, S,
and a source, s                        vertex Q
shortest_paths( Graph g, Node s )
    initialise_single_source( g, s )
    S := { 0 }         /* Make S empty */
    Q := Vertices( g ) /* Put the vertices in a PQ */
    while not Empty(Q)
        u := ExtractCheapest( Q );
        AddNode( S, u ); /* Add u to S */
        for each vertex v in Adjacent( u )
            relax( u, v, w )
Dijkstra’s Algorithm - Loop
  • The Shortest Paths algorithm
Given a graph, g,
and a source, s

shortest_paths( GraphthereNode s )
                While g, are
    initialise_single_source( g, s )
                still nodes in Q
    S := { 0 }           /* Make S empty */
    Q := Vertices( g ) /* Put the vertices in a PQ */
    while not Empty(Q)
        u := ExtractCheapest( Q );             Greedy!
        AddNode( S, u ); /* Add u to S */
        for each vertex v in Adjacent( u )
            relax( u, v, w )
Dijkstra’s Algorithm - Relax neighbours
  • The Shortest Paths algorithm
Given a graph, g,
and a source, s     Update the
                  estimate of the
shortest_paths( Graph g, paths to )
                 shortest Node s
    initialise_single_source( g, s )
                      all nodes
    S := { 0 }     attached to u S empty */
                        /* Make
    Q := Vertices( g ) /* Put the vertices in a PQ */
    while not Empty(Q)
        u := ExtractCheapest( Q );             Greedy!
        AddNode( S, u ); /* Add u to S */
        for each vertex v in Adjacent( u )
            relax( u, v, w )
Dijkstra’s Algorithm - Operation
• Initial Graph

 Source
Mark 0                    Distance to all
                         nodes marked ∞
Dijkstra’s Algorithm - Operation
 • Initial Graph


Source




                        Relax vertices adjacent to
                                 source
Dijkstra’s Algorithm - Operation
 • Initial Graph


Source




                         Red arrows show
                          pre-decessors
Dijkstra’s Algorithm - Operation




Source is now in S        Sort vertices and
                           choose closest
Dijkstra’s Algorithm - Operation
                 Relax u because a
                 shorter path via x
                       exists




Source is now in S                    Relax y because a
                                      shorter path via x
                                            exists
Dijkstra’s Algorithm - Operation



                        Change u’s
                     pre-decessor also




Source is now in S                       Relax y because a
                                         shorter path via x
                                               exists
Dijkstra’s Algorithm - Operation




 S is now { s, x }        Sort vertices and
                           choose closest
Dijkstra’s Algorithm - Operation
                                Relax v because a
                                shorter path via y
                                      exists




 S is now { s, x }
                          Sort vertices and
                           choose closest
Dijkstra’s Algorithm - Operation




 S is now { s, x, y }      Sort vertices and
                           choose closest, u
Dijkstra’s Algorithm - Operation




S is now { s, x, y, u }   Finally add v
Dijkstra’s Algorithm - Operation




S is now { s, x, y, u }     Pre-decessors show
                          shortest paths sub-graph
Dijkstra’s Algorithm - Proof
• Greedy Algorithm
  • Proof by contradiction best
• Lemma 1
  • Shortest paths are composed of shortest paths
• Proof
  • If there was a shorter path than any sub-path, then
    substitution of that path would make the whole path
    shorter
Dijkstra’s Algorithm - Proof
• Denote
    δ(s,v) - the cost of the shortest path from s to v
• Lemma 2
  • If s→...→u→v is a shortest path from s to v,
    then after u has been added to S and relax(u,v,w) called,
    d[v] = δ(s,v) and d[v] is not changed thereafter.
• Proof
  • Follows from the fact that at all times d[v] ≥ δ(s,v)
  • See Cormen (or any other text) for the details
Dijkstra’s Algorithm - Proof
• Using Lemma 2
   • After running Dijkstra’s algorithm, we assert
     d[v] = δ(s,v) for all v
• Proof (by contradiction)
   • Suppose that u is the first vertex added to S for which
     d[u] ≠ δ(s,u)
   • Note
       • v is not s because d[s] = 0
       • There must be a path s→...→u,
         otherwise d[u] would be ∞
       • Since there’s a path, there must be a shortest path
Dijkstra’s Algorithm - Proof
• Proof (by contradiction)
   • Suppose that u is the first vertex added to S for which
     d[u] ≠ δ(s,u)
   • Let s→x→y→u be the shortest path
     s→u,
     where x is in S and y is the
     first outside S
   • When x was added to S, d[x] = δ(s,x)
   • Edge x→y was relaxed at that time,
     so d[y] = δ(s,y)
Dijkstra’s Algorithm - Proof
• Proof (by contradiction)
   • Edge x→y was relaxed at that time,
     so d[y] = δ(s,y)
             ≤ δ(s,u) ≤ d[u]
   • But, when we chose u,
     both u and y where in V-S,
     so d[u] ≤ d[y]
     (otherwise we would have chosen y)
   • Thus the inequalities must be equalities
   ∴ d[y] = δ(s,y) = δ(s,u) = d[u]
   • And our hypothesis (d[u] ≠ δ(s,u)) is contradicted!
Dijkstra’s Algorithm - Time Complexity
• Dijkstra’s Algorithm
   • Similar to MST algorithms
   • Key step is sort on the edges
   • Complexity is
       • O( (|E|+|V|)log|V| ) or
       • O( n2 log n )
         for a dense graph with n = |V|

Mais conteĂşdo relacionado

Mais procurados

Dijkstra's algorithm
Dijkstra's algorithmDijkstra's algorithm
Dijkstra's algorithmgsp1294
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy methodhodcsencet
 
Coin Change Problem
Coin Change ProblemCoin Change Problem
Coin Change ProblemDEVTYPE
 
Dijkstra's Algorithm
Dijkstra's AlgorithmDijkstra's Algorithm
Dijkstra's AlgorithmArijitDhali
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesFahim Ferdous
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithmmeisamstar
 
Dijkstra's algorithm presentation
Dijkstra's algorithm presentationDijkstra's algorithm presentation
Dijkstra's algorithm presentationSubid Biswas
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithmsRajendran
 
Bellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
Bellman-Ford-Moore Algorithm and Dijkstra’s AlgorithmBellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
Bellman-Ford-Moore Algorithm and Dijkstra’s AlgorithmFulvio Corno
 
Bellman ford Algorithm
Bellman ford AlgorithmBellman ford Algorithm
Bellman ford Algorithmtaimurkhan803
 
Dijkstra’S Algorithm
Dijkstra’S AlgorithmDijkstra’S Algorithm
Dijkstra’S Algorithmami_01
 
Dijkstra & flooding ppt(Routing algorithm)
Dijkstra & flooding ppt(Routing algorithm)Dijkstra & flooding ppt(Routing algorithm)
Dijkstra & flooding ppt(Routing algorithm)Anshul gour
 
Floyd Warshall Algorithm
Floyd Warshall AlgorithmFloyd Warshall Algorithm
Floyd Warshall AlgorithmInteX Research Lab
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning treeAmit Kumar Rathi
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtrackingmandlapure
 
Dijkstra’s algorithm
Dijkstra’s algorithmDijkstra’s algorithm
Dijkstra’s algorithmfaisal2204
 

Mais procurados (20)

Dijkstra's algorithm
Dijkstra's algorithmDijkstra's algorithm
Dijkstra's algorithm
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
 
Coin Change Problem
Coin Change ProblemCoin Change Problem
Coin Change Problem
 
Dijkstra's Algorithm
Dijkstra's AlgorithmDijkstra's Algorithm
Dijkstra's Algorithm
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and Examples
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithm
 
Shortest path algorithm
Shortest  path algorithmShortest  path algorithm
Shortest path algorithm
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Dijkstra's algorithm presentation
Dijkstra's algorithm presentationDijkstra's algorithm presentation
Dijkstra's algorithm presentation
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 
Shortest Path in Graph
Shortest Path in GraphShortest Path in Graph
Shortest Path in Graph
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Bellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
Bellman-Ford-Moore Algorithm and Dijkstra’s AlgorithmBellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
Bellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
 
Bellman ford Algorithm
Bellman ford AlgorithmBellman ford Algorithm
Bellman ford Algorithm
 
Dijkstra’S Algorithm
Dijkstra’S AlgorithmDijkstra’S Algorithm
Dijkstra’S Algorithm
 
Dijkstra & flooding ppt(Routing algorithm)
Dijkstra & flooding ppt(Routing algorithm)Dijkstra & flooding ppt(Routing algorithm)
Dijkstra & flooding ppt(Routing algorithm)
 
Floyd Warshall Algorithm
Floyd Warshall AlgorithmFloyd Warshall Algorithm
Floyd Warshall Algorithm
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtracking
 
Dijkstra’s algorithm
Dijkstra’s algorithmDijkstra’s algorithm
Dijkstra’s algorithm
 

Destaque

Mengajar nilai tempat
Mengajar nilai tempatMengajar nilai tempat
Mengajar nilai tempatikmalieyana
 
Nilai tempat suatu bilangan
Nilai tempat suatu bilanganNilai tempat suatu bilangan
Nilai tempat suatu bilanganyulia94
 
Graphs in c language
Graphs in c languageGraphs in c language
Graphs in c languageSARITHA REDDY
 
Ppt pembelajaran
Ppt pembelajaranPpt pembelajaran
Ppt pembelajaranRahmahwati14
 
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra Sahil Kumar
 
Slide teknik pengajaran part 2
Slide teknik pengajaran part 2Slide teknik pengajaran part 2
Slide teknik pengajaran part 2Yim Cecilia
 
Membina 5 ayat
Membina 5 ayatMembina 5 ayat
Membina 5 ayatkamsiahtumin
 
Modul p&p matematik nombor dan operasi thn 2
Modul p&p matematik   nombor dan operasi thn 2Modul p&p matematik   nombor dan operasi thn 2
Modul p&p matematik nombor dan operasi thn 2mazlan81
 
Latihan Menulis Bahasa Melayu Tahun 1
Latihan Menulis Bahasa Melayu Tahun 1Latihan Menulis Bahasa Melayu Tahun 1
Latihan Menulis Bahasa Melayu Tahun 1PAKLONG CIKGU
 
Konsep bilangan, dan lambang bilangan,
Konsep bilangan, dan lambang bilangan,Konsep bilangan, dan lambang bilangan,
Konsep bilangan, dan lambang bilangan,eka noviana
 
Soalan ujian BM Tahun 1 kertas 2
Soalan ujian BM Tahun 1 kertas 2Soalan ujian BM Tahun 1 kertas 2
Soalan ujian BM Tahun 1 kertas 2Azeri Hizlah
 
Kemahiran 32 : Bacaan dan Pemahaman)
Kemahiran 32 : Bacaan dan Pemahaman)Kemahiran 32 : Bacaan dan Pemahaman)
Kemahiran 32 : Bacaan dan Pemahaman)Annur Hayfa
 
Isi hurufberdasarkan gambar
Isi hurufberdasarkan gambarIsi hurufberdasarkan gambar
Isi hurufberdasarkan gambarchowteetan
 
Bina Ayat Berdasarkan Gambar
Bina Ayat Berdasarkan GambarBina Ayat Berdasarkan Gambar
Bina Ayat Berdasarkan GambarKathleen Ong
 
SOALAN KSSR TAHUN 1
SOALAN KSSR TAHUN 1SOALAN KSSR TAHUN 1
SOALAN KSSR TAHUN 1Nsha Shari
 
Bahasa Melayu Pemahaman Tahun 1
Bahasa Melayu Pemahaman Tahun 1Bahasa Melayu Pemahaman Tahun 1
Bahasa Melayu Pemahaman Tahun 1PAKLONG CIKGU
 
17. Trees and Graphs
17. Trees and Graphs17. Trees and Graphs
17. Trees and GraphsIntro C# Book
 

Destaque (18)

Mengajar nilai tempat
Mengajar nilai tempatMengajar nilai tempat
Mengajar nilai tempat
 
Nilai tempat suatu bilangan
Nilai tempat suatu bilanganNilai tempat suatu bilangan
Nilai tempat suatu bilangan
 
Graphs in c language
Graphs in c languageGraphs in c language
Graphs in c language
 
Ppt pembelajaran
Ppt pembelajaranPpt pembelajaran
Ppt pembelajaran
 
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
 
Slide teknik pengajaran part 2
Slide teknik pengajaran part 2Slide teknik pengajaran part 2
Slide teknik pengajaran part 2
 
Membina 5 ayat
Membina 5 ayatMembina 5 ayat
Membina 5 ayat
 
Modul p&p matematik nombor dan operasi thn 2
Modul p&p matematik   nombor dan operasi thn 2Modul p&p matematik   nombor dan operasi thn 2
Modul p&p matematik nombor dan operasi thn 2
 
Latihan Menulis Bahasa Melayu Tahun 1
Latihan Menulis Bahasa Melayu Tahun 1Latihan Menulis Bahasa Melayu Tahun 1
Latihan Menulis Bahasa Melayu Tahun 1
 
Konsep bilangan, dan lambang bilangan,
Konsep bilangan, dan lambang bilangan,Konsep bilangan, dan lambang bilangan,
Konsep bilangan, dan lambang bilangan,
 
Soalan ujian BM Tahun 1 kertas 2
Soalan ujian BM Tahun 1 kertas 2Soalan ujian BM Tahun 1 kertas 2
Soalan ujian BM Tahun 1 kertas 2
 
Kemahiran 32 : Bacaan dan Pemahaman)
Kemahiran 32 : Bacaan dan Pemahaman)Kemahiran 32 : Bacaan dan Pemahaman)
Kemahiran 32 : Bacaan dan Pemahaman)
 
Jom baca 1
Jom baca 1Jom baca 1
Jom baca 1
 
Isi hurufberdasarkan gambar
Isi hurufberdasarkan gambarIsi hurufberdasarkan gambar
Isi hurufberdasarkan gambar
 
Bina Ayat Berdasarkan Gambar
Bina Ayat Berdasarkan GambarBina Ayat Berdasarkan Gambar
Bina Ayat Berdasarkan Gambar
 
SOALAN KSSR TAHUN 1
SOALAN KSSR TAHUN 1SOALAN KSSR TAHUN 1
SOALAN KSSR TAHUN 1
 
Bahasa Melayu Pemahaman Tahun 1
Bahasa Melayu Pemahaman Tahun 1Bahasa Melayu Pemahaman Tahun 1
Bahasa Melayu Pemahaman Tahun 1
 
17. Trees and Graphs
17. Trees and Graphs17. Trees and Graphs
17. Trees and Graphs
 

Semelhante a Dijkstra c

Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithmRuchika Sinha
 
Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10Traian Rebedea
 
Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Naor Ami
 
Dijkstra Searching Algorithms Shortest.pptx
Dijkstra Searching Algorithms Shortest.pptxDijkstra Searching Algorithms Shortest.pptx
Dijkstra Searching Algorithms Shortest.pptxsandeep54552
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docxSeethaDinesh
 
lecture 21
lecture 21lecture 21
lecture 21sajinsc
 
Single source shortes path in dag
Single source shortes path in dagSingle source shortes path in dag
Single source shortes path in dagKiran K
 
04 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x204 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x2MuradAmn
 
Single source stortest path bellman ford and dijkstra
Single source stortest path bellman ford and dijkstraSingle source stortest path bellman ford and dijkstra
Single source stortest path bellman ford and dijkstraRoshan Tailor
 
04 greedyalgorithmsii
04 greedyalgorithmsii04 greedyalgorithmsii
04 greedyalgorithmsiiLENIN Quintero
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithmSrikrishnan Suresh
 
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdfDKTaxation
 
Chap10 slides
Chap10 slidesChap10 slides
Chap10 slidesHJ DS
 
2.6 all pairsshortestpath
2.6 all pairsshortestpath2.6 all pairsshortestpath
2.6 all pairsshortestpathKrish_ver2
 
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
 

Semelhante a Dijkstra c (20)

dijkstraC.ppt
dijkstraC.pptdijkstraC.ppt
dijkstraC.ppt
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 
Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10Algorithm Design and Complexity - Course 10
Algorithm Design and Complexity - Course 10
 
Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14
 
Dijkstra Searching Algorithms Shortest.pptx
Dijkstra Searching Algorithms Shortest.pptxDijkstra Searching Algorithms Shortest.pptx
Dijkstra Searching Algorithms Shortest.pptx
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docx
 
lecture 21
lecture 21lecture 21
lecture 21
 
Single source shortes path in dag
Single source shortes path in dagSingle source shortes path in dag
Single source shortes path in dag
 
04 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x204 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x2
 
Single source stortest path bellman ford and dijkstra
Single source stortest path bellman ford and dijkstraSingle source stortest path bellman ford and dijkstra
Single source stortest path bellman ford and dijkstra
 
Dijksatra
DijksatraDijksatra
Dijksatra
 
04 greedyalgorithmsii
04 greedyalgorithmsii04 greedyalgorithmsii
04 greedyalgorithmsii
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithm
 
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdf
 
Graph 3
Graph 3Graph 3
Graph 3
 
Dijkstra.ppt
Dijkstra.pptDijkstra.ppt
Dijkstra.ppt
 
Dijkstra algorithm
Dijkstra algorithmDijkstra algorithm
Dijkstra algorithm
 
Chap10 slides
Chap10 slidesChap10 slides
Chap10 slides
 
2.6 all pairsshortestpath
2.6 all pairsshortestpath2.6 all pairsshortestpath
2.6 all pairsshortestpath
 
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
 

Último

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
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
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
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
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 

Último (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 

Dijkstra c

  • 1. Data Structures and Algorithms Graphs Single-Source Shortest Paths (Dijkstra’s Algorithm) PLSD210(ii)
  • 2. Graphs - Shortest Paths • Application • In a graph in which edges have costs .. • Find the shortest path from a source to a destination • Surprisingly .. • While finding the shortest path from a source to one destination, • we can find the shortest paths to all over destinations as well! • Common algorithm for single-source shortest paths is due to Edsger Dijkstra
  • 3. Dijkstra’s Algorithm - Data Structures • For a graph, G = ( V, E ) • Dijkstra’s algorithm keeps two sets of vertices: S Vertices whose shortest paths have already been determined V-S Remainder • Also d Best estimates of shortest path to each vertex π Predecessors for each vertex
  • 4. Predecessor Sub-graph • Array of vertex indices, π[j], j = 1 .. |V| • π[j] contains the pre-decessor for node j • j’s predecessor is in π[π[j]], and so on .... • The edges in the pre-decessor sub-graph are ( π[j], j )
  • 5. Dijkstra’s Algorithm - Operation • Initialise d and π • For each vertex, j, in V • dj = ∞ Initial estimates are all ∞ • π j = nil No connections • Source distance, ds = 0 • Set S to empty • While V-S is not empty • Sort V-S based on d Add s first! • Add u, the closest vertex in V-S, to S • Relax all the vertices still in V-S connected to u
  • 6. Dijkstra’s Algorithm - Operation • Initialise d and π • For each vertex, j, in V • dj = ∞ • π j = nil Initial estimates are all ∞ No connections • Source distance, ds = 0 • Set S to empty • While V-S is not empty • Sort V-S based on d • Add u, the closest vertex in V-S, to S Add s first! • Relax all the vertices still in V-S connected to u
  • 7. Dijkstra’s Algorithm - Operation • The Relaxation process Relax the node v attached to node u Edge cost matrix If the current best relax( Node u, Node v, double w[][] ) estimate to v is if d[v] > d[u] + w[u,v] then greater than the d[v] := d[u] + w[u,v] path through u .. pi[v] := u Update the Make v’s predecessor estimate to v point to u
  • 8. Dijkstra’s Algorithm - Full • The Shortest Paths algorithm Given a graph, g, and a source, s shortest_paths( Graph g, Node s ) initialise_single_source( g, s ) S := { 0 } /* Make S empty */ Q := Vertices( g ) /* Put the vertices in a PQ */ while not Empty(Q) u := ExtractCheapest( Q ); AddNode( S, u ); /* Add u to S */ for each vertex v in Adjacent( u ) relax( u, v, w )
  • 9. Dijkstra’s Algorithm - Initialise • The Shortest Paths algorithm Given a graph, g, Initialise d, π, S, and a source, s vertex Q shortest_paths( Graph g, Node s ) initialise_single_source( g, s ) S := { 0 } /* Make S empty */ Q := Vertices( g ) /* Put the vertices in a PQ */ while not Empty(Q) u := ExtractCheapest( Q ); AddNode( S, u ); /* Add u to S */ for each vertex v in Adjacent( u ) relax( u, v, w )
  • 10. Dijkstra’s Algorithm - Loop • The Shortest Paths algorithm Given a graph, g, and a source, s shortest_paths( GraphthereNode s ) While g, are initialise_single_source( g, s ) still nodes in Q S := { 0 } /* Make S empty */ Q := Vertices( g ) /* Put the vertices in a PQ */ while not Empty(Q) u := ExtractCheapest( Q ); Greedy! AddNode( S, u ); /* Add u to S */ for each vertex v in Adjacent( u ) relax( u, v, w )
  • 11. Dijkstra’s Algorithm - Relax neighbours • The Shortest Paths algorithm Given a graph, g, and a source, s Update the estimate of the shortest_paths( Graph g, paths to ) shortest Node s initialise_single_source( g, s ) all nodes S := { 0 } attached to u S empty */ /* Make Q := Vertices( g ) /* Put the vertices in a PQ */ while not Empty(Q) u := ExtractCheapest( Q ); Greedy! AddNode( S, u ); /* Add u to S */ for each vertex v in Adjacent( u ) relax( u, v, w )
  • 12. Dijkstra’s Algorithm - Operation • Initial Graph Source Mark 0 Distance to all nodes marked ∞
  • 13. Dijkstra’s Algorithm - Operation • Initial Graph Source Relax vertices adjacent to source
  • 14. Dijkstra’s Algorithm - Operation • Initial Graph Source Red arrows show pre-decessors
  • 15. Dijkstra’s Algorithm - Operation Source is now in S Sort vertices and choose closest
  • 16. Dijkstra’s Algorithm - Operation Relax u because a shorter path via x exists Source is now in S Relax y because a shorter path via x exists
  • 17. Dijkstra’s Algorithm - Operation Change u’s pre-decessor also Source is now in S Relax y because a shorter path via x exists
  • 18. Dijkstra’s Algorithm - Operation S is now { s, x } Sort vertices and choose closest
  • 19. Dijkstra’s Algorithm - Operation Relax v because a shorter path via y exists S is now { s, x } Sort vertices and choose closest
  • 20. Dijkstra’s Algorithm - Operation S is now { s, x, y } Sort vertices and choose closest, u
  • 21. Dijkstra’s Algorithm - Operation S is now { s, x, y, u } Finally add v
  • 22. Dijkstra’s Algorithm - Operation S is now { s, x, y, u } Pre-decessors show shortest paths sub-graph
  • 23. Dijkstra’s Algorithm - Proof • Greedy Algorithm • Proof by contradiction best • Lemma 1 • Shortest paths are composed of shortest paths • Proof • If there was a shorter path than any sub-path, then substitution of that path would make the whole path shorter
  • 24. Dijkstra’s Algorithm - Proof • Denote δ(s,v) - the cost of the shortest path from s to v • Lemma 2 • If s→...→u→v is a shortest path from s to v, then after u has been added to S and relax(u,v,w) called, d[v] = δ(s,v) and d[v] is not changed thereafter. • Proof • Follows from the fact that at all times d[v] ≥ δ(s,v) • See Cormen (or any other text) for the details
  • 25. Dijkstra’s Algorithm - Proof • Using Lemma 2 • After running Dijkstra’s algorithm, we assert d[v] = δ(s,v) for all v • Proof (by contradiction) • Suppose that u is the first vertex added to S for which d[u] ≠ δ(s,u) • Note • v is not s because d[s] = 0 • There must be a path s→...→u, otherwise d[u] would be ∞ • Since there’s a path, there must be a shortest path
  • 26. Dijkstra’s Algorithm - Proof • Proof (by contradiction) • Suppose that u is the first vertex added to S for which d[u] ≠ δ(s,u) • Let s→x→y→u be the shortest path s→u, where x is in S and y is the first outside S • When x was added to S, d[x] = δ(s,x) • Edge x→y was relaxed at that time, so d[y] = δ(s,y)
  • 27. Dijkstra’s Algorithm - Proof • Proof (by contradiction) • Edge x→y was relaxed at that time, so d[y] = δ(s,y) ≤ δ(s,u) ≤ d[u] • But, when we chose u, both u and y where in V-S, so d[u] ≤ d[y] (otherwise we would have chosen y) • Thus the inequalities must be equalities ∴ d[y] = δ(s,y) = δ(s,u) = d[u] • And our hypothesis (d[u] ≠ δ(s,u)) is contradicted!
  • 28. Dijkstra’s Algorithm - Time Complexity • Dijkstra’s Algorithm • Similar to MST algorithms • Key step is sort on the edges • Complexity is • O( (|E|+|V|)log|V| ) or • O( n2 log n ) for a dense graph with n = |V|