Depth-First
SEARCH
Name : Azim Haider
Id : 1527-2018
Teacher : ma’am Misbah
Search: Look for a given node
stop when node found, even if not all nodes were
visited
Traversal: Always visit all nodes
Similar to Depth-first Traversal of a Binary Tree
Choose a starting vertex
Do a depth-first search on each adjacent vertex
depth-first-search
mark vertex as visited
for each adjacent vertex
if unvisited
do a depth-first search on adjacent vertex
A
B C
D E F G
v
A
B C
D E F G
A
v
A
B C
D E F G
A
v
A
v
B C
D E F G
A B
v
A
v
B C
D E F G
A B
v
A
v
B C
D E F G
A B
v
A
v
B C
v
D E F G
A B D
v
A
v
B C
v
D E F G
A B D
v
A
v
B C
v
D E v F G
A B D E
v
A
v
B C
v
D E F G
A B D
v
A
v
B C
v
D E v F G
A B D E
v
A
v
B C
v
D E v F G
A B D E
v
A
v
B C
v
D E F G
A B D E
v
A
v
B C
v
D E v F G
A B D E
v
A
v
B C
v
D E v F G
A B D E
v
A
v
B C
v
D E v F G
A B D E
v
A
v
B C
v
D E v F G
v
A B D E F
v
A
v
B C
v
D E v F G
v
A B D E F
v
A
v
B C
v
D E v F G
v
A B D E F
v
A
v v
B C
v
D E v F G
v
A B D E F C
v
A
v v
B C
v
D E v F G
v
A B D E F C
v
A
v v
B C
v
D E v F G
v
A B D E F C
v
A
v v
B C
v
D E v F G
v
A B D E F C
v
A
v v
B C
v
v
D E v F G
v
A B D E F C G
v
A
v v
B C
v
v
D E v F G
v
A B D E F C G
v
A
v v
B C
v
v
D E v F G
v
A B D E F C G
v
A
v v
B C
v
v
D E v F G
v
A B D E F C G
v
A
v v
B C
v
v
D E v F G
v
A B D E F C G
v
A
v v
B C
v
v
D E v F G
v
A B D E F C G
v
A
v v
B C
v
v
D E v F G
v
A B D E F C G
v
A
v v
B C
v
v
D E v F G
v
A B D E F C G
A
B C
D E F G
A B D E F C G
Time Complexity
Adjacency Lists
Each node is marked visited once
Each node is checked for each incoming edge
O (v + e)
Adjacency Matrix
Have to check all entries in matrix: O(n2)
Time and Space Complexity
for Depth-First Search
Space Complexity
Stack to handle nodes as they are explored
Worst case: all nodes put on stack (if graph is
linear)
O(n)