CSCI 248: Data Structure and Algorithms II Depth-first search – DFS Algorithm Input: Graph G = (V, E), source vertex s Output: Graph G with its vertices marked by two integers d[v] and f[v] indicate when DFS discovers v and when it finishes v. The process: DFS assumes that adjacency linked-list representation of the graph is used. DFS colors each vertex white, gray, or black. o white means – the vertex in not discovered yet, o gray means the vertex was discovered but their adjacency list is not fully examined yet, o black color means that the vertex was discovered and the adjacency list of that vertex was fully examined. DFS is recursive algorithm DFS creates the Depth-First Forest composed of several Depth-First Trees Color of each vertex v is stored in color[v] Parent of v in the breadth-first tree is stored in p[v] DFS timestamps each vertex: each vertex has two timestamps: d[v] records when v is first discovered ( and grayed), and the second timestamp f[v] records when the search finishes examining v’s adjacency list ( and blackens v). DFS uses global variable time for that purpose. DFS(G, s) 1 for each vertex u in V do 2 color[u] ← white 3 p[u] ← NULL 4 time ← 0 5 for each u in V do 6 if color[u] == white 7 DFS-Visit(u) DFS-Visit(u) //recursive function 1 color[u] ← gray 2 d[u] ← time ← time + 1 3 for each v in adjacency list of u do 4 if color[v] == white 5 p[v] ← u 6 DFS-Visit(v) 7 color[u] ← black 8 f[u] ← time ← time + 1 Running time of DFS is (V+E).
Pages to are hidden for
"CSCI 248: Data Structure and Algorithms II"Please download to view full document