SlideShare a Scribd company logo
1 of 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|

More Related Content

What's hot

Graph in data structure
Graph in data structureGraph in data structure
Graph in data structureAbrish06
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVLKatang Isip
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Shuvongkor Barman
 
Dijkstra's Algorithm
Dijkstra's AlgorithmDijkstra's Algorithm
Dijkstra's AlgorithmArijitDhali
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1Amrinder Arora
 
Bubble sort
Bubble sortBubble sort
Bubble sortManek Ar
 
Algorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsAlgorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsMohamed Loey
 
Complexity analysis - The Big O Notation
Complexity analysis - The Big O NotationComplexity analysis - The Big O Notation
Complexity analysis - The Big O NotationJawad Khan
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithmMohd Arif
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sortMadhu Bala
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in pythonTMARAGATHAM
 
PROCEDURAL ORIENTED PROGRAMMING VS OBJECT ORIENTED PROGRAMING
PROCEDURAL ORIENTED PROGRAMMING VS OBJECT ORIENTED PROGRAMING PROCEDURAL ORIENTED PROGRAMMING VS OBJECT ORIENTED PROGRAMING
PROCEDURAL ORIENTED PROGRAMMING VS OBJECT ORIENTED PROGRAMING Uttam Singh
 
Dijkstra’S Algorithm
Dijkstra’S AlgorithmDijkstra’S Algorithm
Dijkstra’S Algorithmami_01
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure shameen khan
 

What's hot (20)

Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Linked list
Linked listLinked list
Linked list
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
 
Dijkstra's Algorithm
Dijkstra's AlgorithmDijkstra's Algorithm
Dijkstra's Algorithm
 
Chapter 8 ds
Chapter 8 dsChapter 8 ds
Chapter 8 ds
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Unit 1 chapter 1 Design and Analysis of Algorithms
Unit 1   chapter 1 Design and Analysis of AlgorithmsUnit 1   chapter 1 Design and Analysis of Algorithms
Unit 1 chapter 1 Design and Analysis of Algorithms
 
Algorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsAlgorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching Algorithms
 
Complexity analysis - The Big O Notation
Complexity analysis - The Big O NotationComplexity analysis - The Big O Notation
Complexity analysis - The Big O Notation
 
Merge sort and quick sort
Merge sort and quick sortMerge sort and quick sort
Merge sort and quick sort
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
 
Time complexity
Time complexityTime complexity
Time complexity
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in python
 
PROCEDURAL ORIENTED PROGRAMMING VS OBJECT ORIENTED PROGRAMING
PROCEDURAL ORIENTED PROGRAMMING VS OBJECT ORIENTED PROGRAMING PROCEDURAL ORIENTED PROGRAMMING VS OBJECT ORIENTED PROGRAMING
PROCEDURAL ORIENTED PROGRAMMING VS OBJECT ORIENTED PROGRAMING
 
Best,worst,average case .17581556 045
Best,worst,average case .17581556 045Best,worst,average case .17581556 045
Best,worst,average case .17581556 045
 
Dijkstra’S Algorithm
Dijkstra’S AlgorithmDijkstra’S Algorithm
Dijkstra’S Algorithm
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 

Viewers also liked

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
 
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
 
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
 

Viewers also liked (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
 

Similar to 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
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithmmeisamstar
 
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
 

Similar to 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
 
Shortest Path in Graph
Shortest Path in GraphShortest Path in Graph
Shortest Path in Graph
 
Dijksatra
DijksatraDijksatra
Dijksatra
 
04 greedyalgorithmsii
04 greedyalgorithmsii04 greedyalgorithmsii
04 greedyalgorithmsii
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithm
 
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
 

Recently uploaded

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

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|