Sunday, September 30, 2012

Lecture 14: Topological Sort and Depth-first Search

Problem DFS Topological sort Summary Lecture 14: Topological Sort and Depth-first Search CSC2100 Data Structure Yufei Tao CSE department, CUHK April 8, 2011 Problem DFS Topological sort Summary In this lecture, we will discuss a problem called topological sort. Our solution is based on an algorithm called depth-first search, which is another method for traversing a graph. Problem DFS Topological sort Summary 1 Problem Dag Topological sort 2 DFS Rationale Formal description and analysis 3 Topological sort Algorithm Correctness Problem

DFS Topological sort Summary Dag Directed acyclic graph A directed graph G is a dag (directed acyclic graph) if it does not have any cycle. Example a b c d e f g h i a b c d e f g h i The left graph is a dag, but the right is not. Problem DFS Topological sort Summary Topological sort Topological sort problem Problem (Topological sort) Given a dag G = (V , E), find an ordering of V, such that, for each edge (u, v) ∈ E, u precedes v in the ordering. The ordering is called a topological order. Example a b c d e f g h i A topological order: a, b, c, h, d, g, i, f , e. Another: h, a, b, c, d, g, i, f , e. The result is not unique. Problem DFS Topological sort Summary Rationale Depth-first search Before dealing with the topological sort problem, let us first clarify how to perform a depth-first search (DFS) on a graph. At each vertex v, DFS “eagerly” switches to a neighbor of v (unlike BFS that switches only after having inspected all the neighbors of v), as we will see. Note In the sequel, we will say that vertex v is a neighbor of vertex u, if (u, v) ∈ E, namely, there is an edge from u to v. Problem DFS Topological sort Summary Rationale DFS example Example At the beginning, color all vertices white (which means “not visited yet”). Consider a DFS starting from vertex c. a b c d e f g h i Color c as grey (which means “visited, but neighbors not finished yet”). Switch to a white neighbor of c, say e. Problem DFS Topological sort Summary Rationale DFS example (cont.) Example a b c d e f g h i Color e grey. Attempt to switch to a white neighbor of e. As such a neighbor does not exist, color e black (which means “visited, and all neighbors done”). The algorithm then backtracks to c. At c, switch to the next white neighbor of c, i.e., d. Problem DFS Topological sort Summary Rationale DFS example (cont.) Example a b c d e f g h i Color d grey. Switch to a white neighbor of d, i.e., g. Problem DFS Topological sort Summary Rationale DFS example (cont.) Example Access g: Access f :...

Website: www.cse.cuhk.edu.hk | Filesize: -
No of Page(s): 17
Download Lecture 14: Topological Sort and Depth-first Search - CSC2100 Data ....pdf

No comments:

Post a Comment