Escolar Documentos
Profissional Documentos
Cultura Documentos
Reading
Other References
Some slides based on: CSE 326 by S. Wolfman, 2000 24-May-02 CSE 373 - Data Structures - 21 - Topological Sort 2
Topological Sort
142 143 322 321 326 370 341
Topological Sort
Given a digraph G = (V, E) , find a linear ordering of its vertices such that: for any edge (v, w) in E, v precedes w in the ordering
B C A
Problem: Find an order in which all these courses can be taken. Example: 142 370 321 326 421 143 341 401 378 322
378
421
F D
3 24-May-02 CSE 373 - Data Structures - 21 - Topological Sort
In order to take a course, you must take all of its prerequisites first
24-May-02
401
E
4
Any linear ordering in which an arrow goes to the left is not a valid solution
B C A F D
24-May-02
D
CSE 373 - Data Structures - 21 - Topological Sort 8
D
24-May-02
E
9 24-May-02 CSE 373 - Data Structures - 21 - Topological Sort 10
B
Select B. Copy to sorted list. Delete B and its edges.
A B
24-May-02
11
24-May-02
12
C
Select C. Copy to sorted list. Delete C and its edges.
D
Select D. Copy to sorted list. Delete D and its edges.
C F D E A B C D E F A B C D
24-May-02
13
24-May-02
14
E, F
Select E. Copy to sorted list. Delete E and its edges. Select F. Copy to sorted list. Delete F and its edges. A B
Done
C F D E Remove from algorithm and serve.
F E
A B C D
A B C D
15 24-May-02 CSE 373 - Data Structures - 21 - Topological Sort
F
16
24-May-02
Tracking in-degree
Calculate and store In-Degree of all vertices in an array Find vertex with in-degree 0: Search the array Remove its edges: Update the array
0 1 In-Degree array 1 2 2 0
17 24-May-02
A B C D E F
B C D E
18
Remove edges:
|E| edges
B C D E
We need a better way to find the next vertex with degree(v)=0 ...
B
enqueue
0 A 0 B 1 C 1 D
B C D E
Output A B A D
24-May-02
Store each vertexs In-Degree in an array Initialize queue with all in-degree=0 vertices 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
C E
2 E 0 F
21
24-May-02
22
Reduce In-Degree of all vertices adjacent to a vertex and Enqueue any In-Degree 0 vertices:
O(|E|)