1 / 27

Topological Sort

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:

jules
Download Presentation

Topological Sort

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. In general, topological order of a dag is not unique.

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

  4. 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)}

  5. 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)

  6. Homework • Page 193: # 2, 3, 6

More Related