Professional Documents
Culture Documents
Lecture 20: Topo-Sort and Dijkstra's Greedy Idea: Items On Today's Lunch Menu
Lecture 20: Topo-Sort and Dijkstra's Greedy Idea: Items On Today's Lunch Menu
R. Rao, CSE 326 Some slides based on: CSE 326 by S. Wolfman, 2000 1
322
143
321
142 326
370 341
B
C
A
F
D E
Topological Sort
Topological sorting problem: given digraph G = (V, E) ,
find a linear ordering of vertices such that:
for any edge (v, w) in E, v precedes w in the ordering
B
C Any linear ordering in which
A all the arrows go to the right
F is a valid solution
D E
A B F C D E
D E
A B E C D F
B
C
A
F
D E
B
C
A
D E
B
C
F A
D E
B
C
F A
D E
Select
C
F A B
D E
Select
A B F
D E
Final Result:
A B F C D E
Problem:
Need a faster way to find vertices with in-degree 0
instead of searching through entire in-degree array
Queue F B
dequeue
enqueue 0 A B D
Output A
0 B C
B 1 C D E
C
A F 1 D E
D E 2 E
In-Degree Adjacency
R. Rao, CSE 326
array 0 F list 18
Topological Sort Algorithm #2
1. Store each vertex’s In-Degree in an array
2. Initialize a queue with all in-degree zero vertices
3. While there are vertices remaining in the queue:
➭ Dequeue and output a vertex
➭ Reduce In-Degree of all vertices adjacent to it by 1
➭ Enqueue any of these vertices whose In-Degree became
zero
B C
A F
Chicago
A B F H
G
C Source
D
E
G
C
D
On-board E
example:
Find the shortest path from C to: A B C D E F G H