Presentation is loading. Please wait.

Presentation is loading. Please wait.

Depth-First Search D B A C E Depth-First Search Depth-First Search

Similar presentations


Presentation on theme: "Depth-First Search D B A C E Depth-First Search Depth-First Search"— Presentation transcript:

1 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

2 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

3 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

4 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

5 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

6 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

7 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

8 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


Download ppt "Depth-First Search D B A C E Depth-First Search Depth-First Search"

Similar presentations


Ads by Google