SlideShare a Scribd company logo
1 of 26
Download to read offline
1
Chapter 9: Graphs
(Topological Sort & Shortest Path
Algorithms)
Text: Read Weiss, §9.1 – 9.3
2
Definitions - I
• A graph G=(V, E) consists of a set of vertices,
V, and a set of edges, E.
• Each edge is a pair (v, w), where v, w є V.
• If the pair is ordered then G is directed
(digraph).
• Vertex w is adjacent to v iff (v, w) є E.
• In an undirected graph with edge (v, w), w is
adjacent to v and v is adjacent to w.
• Sometimes an edge has a third component,
weight or cost.
3
Definitions - II
• A path in a graph is w1, w2,...,wN such that
(wi, wi+1) є E for 1≤i<N. The length of such
a path is the number of edges on the path.
If a path from a vertex to itself contains no
edges, then the path length is zero. If G
contains an edge (v, v), then the path v, v
is called a loop.
• A simple path is a path such that all
vertices are distinct, except that the first
and the last could be the same.
4
Definitions - III
• A cycle in a directed graph is a path of length at
least 1 such that w1=wN. This cycle is simple if the
path is simple. For undirected graphs, the edges are
required to be distinct (Why?).
• A directed graph is acyclic if it has no cycles (DAG).
• An undirected graph is connected if there is a path
from every vertex to every other vertex. A directed
graph with this property is called strongly
connected. If directed graph is not, but underlying
undirected graph is, it is weakly connected. A
complete graph is a graph in which there is an
edge between every pair of vertices.
5
Representation of Graphs - I
• One simple way is to use a two-
dimensional array (adjacency matrix
representation). If vertices are numbered
starting at 1, A[u][v]=true if (u, v) є E.
Space requirement is Θ(|V|2).
• If the graph is not dense (sparse),
adjacency lists may be used. The space
requirement is O(|E|+|V|).
6
Representation of Graphs - II
7
Topological Sort - I
•A topological sort is an ordering of vertices
in a DAG, such that if there is path from vi to
vj, then vj appears after vi in the ordering.
•A simple algorithm to find a topological
ordering is first to find any vertex with no
incoming edges. We can then print this vertex,
and remove it, along with its edges. Then apply
the same strategy to the rest of the graph. To
formalize this, define the indegree of a vertex
v as the number of edges (u, v).
8
Topological Sort – Initial Attempt
• running time of
the algorithm is
O(|V|2).
9
• We can remove the inefficiency by
keeping all the unassigned vertices
of indegree 0 in a special data
structure (queue or stack). When a
new vertex with degree zero is
needed, it is returned by removing
one from the queue, and when the
indegrees of adjacent vertices are
decremented, they are inserted into
the queue if the indegree falls to
zero. The running time is O(|E|+|V|)
Topological Sort – A Better Algorithm
10
Shortest-Path Algorithms
• The input is a weighted graph: associated
with each edge (vi, vj) is a cost ci,j. The
cost of a path v1v2...vN is ∑ci,i+1 for i in
[1..N-1]. This is weighted path length, the
unweighted path length on the other
hand is merely the number of edges on
the path, namely, N-1.
• Single-source Shortest-Path Problem:
Given as input a weighted graph G=(V, E),
and a distinguished vertex, s, find the
shortest weighted path from s to every
other vertex in G.
Shortest-Path Algorithms (cont.)
11
• In the graph below, the shortest path from v1 to v6 has a cost
of 6 and the path itself is v1v4v7v6. The shortest unweighted
path has 2 edges.
Negative Cost Cycles
12
• In the graph shown, we have a negative cost. The path from
v5 to v4 has cost 1, but a shorter path exists by following the
loop v5v4v2v5v4 which has cost -5. This path is still not the
shortest, because we could stay in the loop arbitrarily long.
Shortest Path Length: Problems
We will examine 4 algorithms to solve four versions of
the problem
1.Unweighted shortest path O(|E|+|V|)
2.Weighted shortest path without negative edges
O(|E|log|V|) using queues
3.Weighted shortest path with negative edges
O(|E| . |V|)
4.Weighted shortest path of acyclic graphs linear
time 13
Unweighted Shortest Paths
• Using some vertex, s, which is an input
parameter, find the shortest path from s to all
other vertices in an unweighted graph. Assume
s=v3.
14
Unweighted Shortest Paths
• Algorithm: find vertices that are at
distance 1, 2, ... N-1 by processing
vertices in layers (breadth-first search)
15
Unweighted Shortest Paths
16
Unweighted Shortest Paths
• Complexity O(|V|2)
17
Unweighted Shortest Paths - Improvement
• At any point in time there
are only two types of
unknown vertices that
have dv≠∞. Some have
dv = currDist and the rest
have dv = currDist +1.
• We can make use of a
queue data structure.
• O(|E|+|V|)
18
Weighted Shortest Path
Dijkstra’s Algorithm
• With weighted shortest path,distance dv is
tentative. It turns out to be the shortest path
length from s to v using only known vertices as
intermediates.
• Greedy algorithm: proceeds in stages doing the
best at each stage. Dijkstra’s algorithm selects a
vertex v with smallest dv among all unknown
vertices and declares it known. Remainder of the
stage consists of updating the values dw for all
edges (v, w).
19
Dijkstra’s Algorithm - Example
20
►
►
►
Dijkstra’s Algorithm - Example
• A proof by contradiction will show that this
algorithm always works as long as no
edge has a negative cost.
21
►
►
►
►
Dijkstra’s Algorithm - Pseudocode
• If the vertices are
sequentially scanned to
find minimum dv, each
phase will take O(|V|) to
find the minimum, thus
O(|V|2) over the course
of the algorithm.
• The time for updates is
constant and at most
one update per edge for
a total of O(|E|).
• Therefore the total time
spent is O(|V|2+|E|).
• If the graph is dense,
OPTIMAL.
22
Dijkstra’s Algorithm-What if the
graph is sparse?
• If the graph is sparse |E|=θ(|V|), algorithm is too
slow. The distances of vertices need to be kept
in a priority queue.
• Selection of vertex with minimum distance via
deleteMin, and updates via decreaseKey
operation. Hence; O(|E|log|V|+|V|log|V|)
• find operations are not supported, so you need
to be able to maintain locations of di in the heap
and update them as they change.
• Alternative: insert w and dw with every update.
23
Graphs with negative edge
costs
• Dijkstra’s algorithm does not work with
negative edge costs. Once a vertex u is
known, it is possible that from some other
unknown vertex v, there is a path back to
u that is very negative.
• Algorithm: A combination of weighted and
unweighted algorithms. Forget about the
concept of known vertices.
24
Graphs with negative edge costs - I
• O(|E|*|V|). Each vertex
can dequeue at most
O(|V|) times. (Why?
Algorithm computes
shortest paths with at
most 0, 1, ..., |V|-1 edges
in this order). Hence, the
result!
• If negative cost cycles,
then each vertex should
be checked to have been
dequeued at most |V|
times.
25
Acyclic Graphs
• If the graph is known to be acyclic, the
order in which vertices are declared
known, can be set to be the topological
order.
• Running time = O(|V|+|E|)
• This selection rule works because when a
vertex is selected, its distance can no
longer be lowered, since by topological
ordering rule it has no incoming edges
emanating from unknown nodes.
26

More Related Content

What's hot

What's hot (20)

All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithm
 
Adjacency list
Adjacency listAdjacency list
Adjacency list
 
(floyd's algm)
(floyd's algm)(floyd's algm)
(floyd's algm)
 
Shortest path problem
Shortest path problemShortest path problem
Shortest path problem
 
Graphs in Data Structure
Graphs in Data StructureGraphs in Data Structure
Graphs in Data Structure
 
Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]
 
Graph Algorithms: Breadth-First Search (BFS)
Graph Algorithms: Breadth-First Search (BFS)Graph Algorithms: Breadth-First Search (BFS)
Graph Algorithms: Breadth-First Search (BFS)
 
Problem Solving with Algorithms and Data Structure - Graphs
Problem Solving with Algorithms and Data Structure - GraphsProblem Solving with Algorithms and Data Structure - Graphs
Problem Solving with Algorithms and Data Structure - Graphs
 
2.5 graph dfs
2.5 graph dfs2.5 graph dfs
2.5 graph dfs
 
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)
 
d
dd
d
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithm
 
1535 graph algorithms
1535 graph algorithms1535 graph algorithms
1535 graph algorithms
 
Graphs data Structure
Graphs data StructureGraphs data Structure
Graphs data Structure
 
Topological Sort
Topological SortTopological Sort
Topological Sort
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
Graph
GraphGraph
Graph
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Shortest Path Problem
Shortest Path ProblemShortest Path Problem
Shortest Path Problem
 
Data Structure Graph DMZ #DMZone
Data Structure Graph DMZ #DMZoneData Structure Graph DMZ #DMZone
Data Structure Graph DMZ #DMZone
 

Similar to 14 chapter9 graph_algorithmstopologicalsort_shortestpath

Similar to 14 chapter9 graph_algorithmstopologicalsort_shortestpath (20)

Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14
 
Algorithm Exam Help
Algorithm Exam Help Algorithm Exam Help
Algorithm Exam Help
 
Unit 2: All
Unit 2: AllUnit 2: All
Unit 2: All
 
graph ASS (1).ppt
graph ASS (1).pptgraph ASS (1).ppt
graph ASS (1).ppt
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptx
 
DIGITAL TEXT BOOK
DIGITAL TEXT BOOKDIGITAL TEXT BOOK
DIGITAL TEXT BOOK
 
Chap10 slides
Chap10 slidesChap10 slides
Chap10 slides
 
Daa chpater14
Daa chpater14Daa chpater14
Daa chpater14
 
Dijkstra.ppt
Dijkstra.pptDijkstra.ppt
Dijkstra.ppt
 
Unit V - ppt.pptx
Unit V - ppt.pptxUnit V - ppt.pptx
Unit V - ppt.pptx
 
Graphs
GraphsGraphs
Graphs
 
Graph 1
Graph 1Graph 1
Graph 1
 
UNIT III.pptx
UNIT III.pptxUNIT III.pptx
UNIT III.pptx
 
6. Graphs
6. Graphs6. Graphs
6. Graphs
 
Graph representation
Graph representationGraph representation
Graph representation
 
Graph
GraphGraph
Graph
 
Graphs
GraphsGraphs
Graphs
 
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjteUnit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
 
Graphs.pptx
Graphs.pptxGraphs.pptx
Graphs.pptx
 
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
 

More from SSE_AndyLi

Chapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsChapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsSSE_AndyLi
 
Chapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsChapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsSSE_AndyLi
 
Chapter 5 introduction to VHDL
Chapter 5 introduction to VHDLChapter 5 introduction to VHDL
Chapter 5 introduction to VHDLSSE_AndyLi
 
Chapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicChapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicSSE_AndyLi
 
Chapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesChapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesSSE_AndyLi
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsSSE_AndyLi
 
15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mstSSE_AndyLi
 
10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queuesSSE_AndyLi
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avlSSE_AndyLi
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bstSSE_AndyLi
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binarySSE_AndyLi
 
6 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart36 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart3SSE_AndyLi
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2SSE_AndyLi
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1SSE_AndyLi
 
3 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart23 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart2SSE_AndyLi
 
2 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart12 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart1SSE_AndyLi
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introductionSSE_AndyLi
 

More from SSE_AndyLi (17)

Chapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsChapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic Circuits
 
Chapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsChapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic Functions
 
Chapter 5 introduction to VHDL
Chapter 5 introduction to VHDLChapter 5 introduction to VHDL
Chapter 5 introduction to VHDL
 
Chapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicChapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational Logic
 
Chapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesChapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and Gates
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital Systems
 
15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst
 
10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avl
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bst
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
 
6 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart36 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart3
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1
 
3 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart23 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart2
 
2 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart12 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart1
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introduction
 

Recently uploaded

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 

Recently uploaded (20)

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 

14 chapter9 graph_algorithmstopologicalsort_shortestpath

  • 1. 1 Chapter 9: Graphs (Topological Sort & Shortest Path Algorithms) Text: Read Weiss, §9.1 – 9.3
  • 2. 2 Definitions - I • A graph G=(V, E) consists of a set of vertices, V, and a set of edges, E. • Each edge is a pair (v, w), where v, w є V. • If the pair is ordered then G is directed (digraph). • Vertex w is adjacent to v iff (v, w) є E. • In an undirected graph with edge (v, w), w is adjacent to v and v is adjacent to w. • Sometimes an edge has a third component, weight or cost.
  • 3. 3 Definitions - II • A path in a graph is w1, w2,...,wN such that (wi, wi+1) є E for 1≤i<N. The length of such a path is the number of edges on the path. If a path from a vertex to itself contains no edges, then the path length is zero. If G contains an edge (v, v), then the path v, v is called a loop. • A simple path is a path such that all vertices are distinct, except that the first and the last could be the same.
  • 4. 4 Definitions - III • A cycle in a directed graph is a path of length at least 1 such that w1=wN. This cycle is simple if the path is simple. For undirected graphs, the edges are required to be distinct (Why?). • A directed graph is acyclic if it has no cycles (DAG). • An undirected graph is connected if there is a path from every vertex to every other vertex. A directed graph with this property is called strongly connected. If directed graph is not, but underlying undirected graph is, it is weakly connected. A complete graph is a graph in which there is an edge between every pair of vertices.
  • 5. 5 Representation of Graphs - I • One simple way is to use a two- dimensional array (adjacency matrix representation). If vertices are numbered starting at 1, A[u][v]=true if (u, v) є E. Space requirement is Θ(|V|2). • If the graph is not dense (sparse), adjacency lists may be used. The space requirement is O(|E|+|V|).
  • 7. 7 Topological Sort - I •A topological sort is an ordering of vertices in a DAG, such that if there is path from vi to vj, then vj appears after vi in the ordering. •A simple algorithm to find a topological ordering is first to find any vertex with no incoming edges. We can then print this vertex, and remove it, along with its edges. Then apply the same strategy to the rest of the graph. To formalize this, define the indegree of a vertex v as the number of edges (u, v).
  • 8. 8 Topological Sort – Initial Attempt • running time of the algorithm is O(|V|2).
  • 9. 9 • We can remove the inefficiency by keeping all the unassigned vertices of indegree 0 in a special data structure (queue or stack). When a new vertex with degree zero is needed, it is returned by removing one from the queue, and when the indegrees of adjacent vertices are decremented, they are inserted into the queue if the indegree falls to zero. The running time is O(|E|+|V|) Topological Sort – A Better Algorithm
  • 10. 10 Shortest-Path Algorithms • The input is a weighted graph: associated with each edge (vi, vj) is a cost ci,j. The cost of a path v1v2...vN is ∑ci,i+1 for i in [1..N-1]. This is weighted path length, the unweighted path length on the other hand is merely the number of edges on the path, namely, N-1. • Single-source Shortest-Path Problem: Given as input a weighted graph G=(V, E), and a distinguished vertex, s, find the shortest weighted path from s to every other vertex in G.
  • 11. Shortest-Path Algorithms (cont.) 11 • In the graph below, the shortest path from v1 to v6 has a cost of 6 and the path itself is v1v4v7v6. The shortest unweighted path has 2 edges.
  • 12. Negative Cost Cycles 12 • In the graph shown, we have a negative cost. The path from v5 to v4 has cost 1, but a shorter path exists by following the loop v5v4v2v5v4 which has cost -5. This path is still not the shortest, because we could stay in the loop arbitrarily long.
  • 13. Shortest Path Length: Problems We will examine 4 algorithms to solve four versions of the problem 1.Unweighted shortest path O(|E|+|V|) 2.Weighted shortest path without negative edges O(|E|log|V|) using queues 3.Weighted shortest path with negative edges O(|E| . |V|) 4.Weighted shortest path of acyclic graphs linear time 13
  • 14. Unweighted Shortest Paths • Using some vertex, s, which is an input parameter, find the shortest path from s to all other vertices in an unweighted graph. Assume s=v3. 14
  • 15. Unweighted Shortest Paths • Algorithm: find vertices that are at distance 1, 2, ... N-1 by processing vertices in layers (breadth-first search) 15
  • 17. Unweighted Shortest Paths • Complexity O(|V|2) 17
  • 18. Unweighted Shortest Paths - Improvement • At any point in time there are only two types of unknown vertices that have dv≠∞. Some have dv = currDist and the rest have dv = currDist +1. • We can make use of a queue data structure. • O(|E|+|V|) 18
  • 19. Weighted Shortest Path Dijkstra’s Algorithm • With weighted shortest path,distance dv is tentative. It turns out to be the shortest path length from s to v using only known vertices as intermediates. • Greedy algorithm: proceeds in stages doing the best at each stage. Dijkstra’s algorithm selects a vertex v with smallest dv among all unknown vertices and declares it known. Remainder of the stage consists of updating the values dw for all edges (v, w). 19
  • 20. Dijkstra’s Algorithm - Example 20 ► ► ►
  • 21. Dijkstra’s Algorithm - Example • A proof by contradiction will show that this algorithm always works as long as no edge has a negative cost. 21 ► ► ► ►
  • 22. Dijkstra’s Algorithm - Pseudocode • If the vertices are sequentially scanned to find minimum dv, each phase will take O(|V|) to find the minimum, thus O(|V|2) over the course of the algorithm. • The time for updates is constant and at most one update per edge for a total of O(|E|). • Therefore the total time spent is O(|V|2+|E|). • If the graph is dense, OPTIMAL. 22
  • 23. Dijkstra’s Algorithm-What if the graph is sparse? • If the graph is sparse |E|=θ(|V|), algorithm is too slow. The distances of vertices need to be kept in a priority queue. • Selection of vertex with minimum distance via deleteMin, and updates via decreaseKey operation. Hence; O(|E|log|V|+|V|log|V|) • find operations are not supported, so you need to be able to maintain locations of di in the heap and update them as they change. • Alternative: insert w and dw with every update. 23
  • 24. Graphs with negative edge costs • Dijkstra’s algorithm does not work with negative edge costs. Once a vertex u is known, it is possible that from some other unknown vertex v, there is a path back to u that is very negative. • Algorithm: A combination of weighted and unweighted algorithms. Forget about the concept of known vertices. 24
  • 25. Graphs with negative edge costs - I • O(|E|*|V|). Each vertex can dequeue at most O(|V|) times. (Why? Algorithm computes shortest paths with at most 0, 1, ..., |V|-1 edges in this order). Hence, the result! • If negative cost cycles, then each vertex should be checked to have been dequeued at most |V| times. 25
  • 26. Acyclic Graphs • If the graph is known to be acyclic, the order in which vertices are declared known, can be set to be the topological order. • Running time = O(|V|+|E|) • This selection rule works because when a vertex is selected, its distance can no longer be lowered, since by topological ordering rule it has no incoming edges emanating from unknown nodes. 26