460 likes | 1.18k Views
Topological Sort. Directed Acyclic Graph (dag): a directed graph which contains no directed cycles. A topological order for a dag G: a sequential listing of all the vertices of G such that if (u,v) E(G) then u precedes v in the listing. Topological Sort:
E N D
Topological Sort Directed Acyclic Graph (dag): a directed graph which contains no directed cycles. A topological order for a dag G: a sequential listing of all the vertices of G such that if (u,v) E(G) then u precedes v in the listing. Topological Sort: an algorithm that takes as input a dag G and produces a topological order of the vertices of G Example Applications: ·Prerequisites dag for courses at a University ·Glossary of technical terms: (t1,t2) E(G) iff t1 is used in the definition of t2.
We will now apply dfs and bfs to the topological sort problem. For dfs, the idea is to find vertices with no successors; these vertices may be placed at the end of the list. Such a vertex may be found by probing as deep as possible along edges, which is what dfs does. Then when all successors of a vertex have been placed in the list, that vertex may be placed. This corresponds to backing out of a vertex when you have completed the exploration from that vertex in dfs. Thus when we are ready to back out from a vertex, we add it to the list in the back-to-front order. Thus dfs will fill the list from the end of the list back toward the first entry.
Code for DFS Topological Sort • Input parameter: adj Output parameter: ts • top_sort( adj, ts ) { n = adj_last k = n // placement index for values into the array ts for I = 1 to n visit[i] = false for I = 1 to n if ( !visit[i] ) top_sort_recurs(adj, i, ts)}
Code for DFS Topological Sort • top_sort_recurs( adj, start, ts ) { visit[start] = true trav = adj[start] while ( trav != null ) { v = trav.ver if ( !visit[v] ) top_sort_recurs(adj, v, ts) trav = trav.next } ts[k] = start k = k-1} • By an analysis similar to that for regular dfs, the running time is (n + m)
Homework • Page 193: # 2, 3, 6