40
DepthFirst Search
Written by Vincent Ngo
Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as
text.
In the previous chapter, you looked at breadthfirst search (BFS), in which you had to explore every neighbor of a vertex before going to the next level. In this chapter, you will look at depthfirst search (DFS), another algorithm for traversing or searching a graph.
There are a lot of applications for DFS:
 Topological sorting.
 Detecting a cycle.
 Pathfinding, such as in maze puzzles.
 Finding connected components in a sparse graph.
To perform a DFS, you start with a given source vertex and attempt to explore a branch as far as possible until you reach the end. At this point, you would backtrack (move a step back) and explore the next available branch until you find what you are looking for or until you’ve visited all the vertices.
Example
Let’s go through a DFS example. The example graph below is the same as the previous chapter. This is so you can see the difference between BFS and DFS.
You will use a stack to keep track of the levels you move through. The stack’s lastinfirstout approach helps with backtracking. Every push on the stack means that you move one level deeper. You can pop to return to a previous level if you reach a dead end.
 As in the previous chapter, you choose
A
as a starting vertex and add it to the stack.  As long as the stack is not empty, you visit the top vertex on the stack and push the first neighboring vertex that has yet to be visited. In this case, you visit
A
and pushB
.
Recall from the previous chapter that the order in which you add edges influences the result of a search. In this case, the first edge added to
A
was an edge toB
, soB
is pushed first.
 You visit
B
and pushE
becauseA
is already visited.  You visit
E
and pushF
.
Note that every time you push on the stack, you advance farther down a branch. Instead of visiting every adjacent vertex, you continue down a path until you reach the end and then backtrack.

You visit
F
and pushG
. 
You visit
G
and pushC
.

The next vertex to visit is
C
. It has neighbors[A, F, G]
, but all of these have been visited. You have reached a dead end, so it’s time to backtrack by poppingC
off the stack. 
This brings you back to
G
. It has neighbors[F, C]
, but all of these have been visited. Another dead end, popG
.

F
also has no unvisited neighbors remaining, so popF
. 
Now, you’re back at
E
. Its neighborH
is still unvisited, so you pushH
on the stack.
 Visiting
H
results in another dead end, so popH
. 
E
also doesn’t have any available neighbors, so pop it.

The same is true for
B
, so popB
. 
This brings you all the way back to
A
, whose neighborD
still needs to be visited, so you pushD
on the stack.
 Visiting
D
results in another dead end, so popD
.  You’re back at
A
, but this time, there are no available neighbors to push, so you popA
. The stack is now empty and the DFS is complete.
When exploring the vertices, you can construct a treelike structure, showing the branches you’ve visited. You can see how deep DFS went compared to BFS.
Implementation
Open up the starter playground for this chapter. This playground contains an implementation of a graph, as well as a stack, which you’ll use to implement DFS.
extension Graph where Element: Hashable {
func depthFirstSearch(from source: Vertex<Element>)
> [Vertex<Element>] {
var stack: Stack<Vertex<Element>> = []
var pushed: Set<Vertex<Element>> = []
var visited: [Vertex<Element>] = []
stack.push(source)
pushed.insert(source)
visited.append(source)
// more to come ...
return visited
}
}
outer: while let vertex = stack.peek() { // 1
let neighbors = edges(from: vertex) // 2
guard !neighbors.isEmpty else { // 3
stack.pop()
continue
}
for edge in neighbors { // 4
if !pushed.contains(edge.destination) {
stack.push(edge.destination)
pushed.insert(edge.destination)
visited.append(edge.destination)
continue outer // 5
}
}
stack.pop() // 6
}
let vertices = graph.depthFirstSearch(from: a)
vertices.forEach { vertex in
print(vertex)
}
0: A
1: B
4: E
5: F
6: G
2: C
7: H
3: D
Performance
DFS will visit every single vertex at least once. This process has a time complexity of O(V).
Key points
 Depthfirst search (DFS) is another algorithm to traverse or search a graph.
 DFS explores a branch as far as possible until it reaches the end.
 Leverage a stack data structure to keep track of how deep you are in the graph. Only pop off the stack when you reach a dead end.