Depth-First Search Review Preorder and Postorder traversals of trees. Visiting Nodes Only Once How do you visit each node in a graph exactly once? How do you avoid visiting a node multiple times? 1. mark nodes when they are visited 2. check the mark before visiting a node Depth-First Order In what order are nodes visited when doing a Depth-First Search? 1. first visit nodes along a single path until the path ends 2. then backup and visit nodes along alternate paths a. start at a node and recursively visit connected nodes b. similar to preorder and postorder traversals of trees List the order in which the nodes are visited when traversing the directed graph Depth-First starting with node c. (When there is a choice of nodes to visit, choose the one that is first in alphabetic order.) (graph3.pdf) V = { a, b, c, d, e, f } E = { (a,b), (a,d), (b,d), (b,e), (c,b), (c,f), (e,a), (e,d), (f,b), (f,e) } a---b---c | X | \ | d---e---f Classwork You may work with a partner. List the order in which the nodes are visited when traversing the directed graph Depth-First starting with node d. (When there is a choice of nodes to visit, choose the one that is first in alphabetic order.) (graph2.pdf) V = { a, b, c, d, e } E = { (b,a), (b,c), (b,d), (b,e), (c,b), (d,c), (d,e), (e,a) } a---b---c \ / \ / e---d Depth-First Search Code What's the code for Depth-First Search? dfs(Node x) mark x visited for each node y that is adjacent to node x if node y is not marked dfs(y) end if end for end dfs What data structure is used to store the nodes that have not yet been visited in a Depth-First Search? What's the Big-Oh for the running time of Depth-First Search? O(1) work for each node and each edge