Depth-First Search D B A C E Depth-First Search Depth-First Search 2/19/2019 6:58 AM Depth-First Search D B A C E Depth-First Search
Depth-First Search Depth-first search (DFS) is a general technique for traversing a graph Similar to Pre-order traversal of a tree “children” -> neighbors level -> number of edges away from starting vertex Not to visit the same vertex more than once Depth-First Search
Depth-first Search Algorithm DFS(G, v) visit v setLabel(v, VISITED) neighbors getAdjacentVertices(G, v) for each w neighbors if getLabel(w) != VISITED // “children” DFS(G, w) Depth-First Search
Depth-first Search The book uses an iterative algorithm same as BFS Algorithm DFS(G, v) visit v setLabel(v, VISITED) neighbors getAdjacentVertices(G, v) for each w neighbors if getLabel(w) != VISITED // “children” DFS(G, w) The book uses an iterative algorithm same as BFS the DFS alg. uses a stack instead of a queue as the container C With recursion, we don’t need to manipulate a stack. Depth-First Search
Example unexplored vertex visited vertex unexplored edge B A C E A A visited vertex unexplored edge discovery edge back edge D B A C E D B A C E Depth-First Search
Example (cont.) D B A C E D B A C E D B A C E D B A C E Depth-First Search
Analysis of DFS Setting/getting a vertex/edge label takes O(1) time Each vertex is labeled twice once as UNEXPLORED once as VISITED O(n) getAdjacentVertices() is called once for each vertex Each edge in the graph is used as most twice Each edge has two vertices O(m) DFS runs in O(n + m) time provided the graph is represented by the adjacency list structure [less precisely, since m is O(n2), BFS is also O(n2)] Depth-First Search
Properties of DFS Property 1 Property 2 DFS(G, v) visits all the vertices and edges in the connected component of v Property 2 The discovery edges labeled by DFS(G, v) form a spanning tree of the connected component of v D B A C E Depth-First Search