next up previous
Next: Examples Up: CSE 2320: Algorithms and Previous: Depth-First Search

DFS

\(1. \;\;\;\) Given G
\(2. \;\;\;\;\;\;\) Pick an unvisited vertex v, remember the rest
\(3. \;\;\;\;\;\;\) Recurse on vertices adjacent to v

DFS(G)
$\;\;\;\;\;$foreach v in V
$\;\;\;\;\;$ $\;\;\;\;\;$visited(v) = True
$\;\;\;\;\;$ $\;\;\;\;\;$pred(v) = NIL
$\;\;\;\;\;$time = 0
$\;\;\;\;\;$foreach u in V
$\;\;\;\;\;$ $\;\;\;\;\;$if not visited(u)
$\;\;\;\;\;$ $\;\;\;\;\;$then Visit(u)



Visit(u)
$\;\;\;\;\;$visited(u) = True
$\;\;\;\;\;$time = time + 1
$\;\;\;\;\;$discover(u) = time
$\;\;\;\;\;$foreach v in Adj[u] $\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$; $\Theta(E)$
$\;\;\;\;\;$ $\;\;\;\;\;$if not visited(v)
$\;\;\;\;\;$ $\;\;\;\;\;$then pred(v) = u
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$Visit(v)
$\;\;\;\;\;$time = time + 1
$\;\;\;\;\;$finished(u) = time



The total running time for DFS is $\Theta(V+E)$



Copyright © 1998 The University of Texas at Arlington