Depth-first search (DFS) [00M6]
- September 17, 2026
DFS introduction and intuition [00M7]
- September 17, 2026
The first graph algorithm we will learn about can answer simple questions of connectivity: given a graph G and particular vertices s and t, are they connected by a path? If so, what is one such path?
The basic idea is to explore as far as you can in a certain direction before backtracking and continuing to explore further unexplored paths, and so on, just like you might explore a physical maze. The problem is loops: we need some way to mark vertices that we have already visited, so we know if we have been somewhere before and don’t get stuck exploring a loop forever. Just like we might mark where we have been by placing rocks on the ground in a physical maze, we can mark previously visited vertices with "digital rocks" so we don't get caught in a loop.
Algorithm DFS (version 1) [00M8]
- September 17, 2026
Notice that we implement DFS via recursion. Perhaps you have also seen a version that uses an explicit stack data structure. By using recursion, we essentially get our programming language's runtime system to keep track of the stack for us. Maintaining a stack ourselves can get annoying and messy, especially if we want to create any extra local variables during the DFS. However, a word of caution: using recursion in this way does not work so well in certain languages (where by "certain languages" I mean "Python"), especially if the graph is large.
To see if vertices s and t are connected, we can just run \mathsf {DFS}(G, s) and see if t is marked visited. Optionally, we can also stop early as soon as we find t during the DFS (left as an exercise).
Correctness of DFS [00MB]
- September 18, 2026
How do we know that DFS does what we want? First of all, we need to argue that it won't go off into an inifinite loop or infinite recursion.
Theorem DFS terminates [00MC]
- September 18, 2026
For any finite graph G and any unvisited vertex u, \mathsf {DFS}(G,u):
- terminates in finite time, and
- decreases the number of unvisited vertices.
Proof.
- September 18, 2026
- If u is the only unvisited vertex, then the \mathsf {if} statement inside the loop will never be true, so \mathsf {DFS} will never call itself recursively and will terminate after iterating through all the neighbors of u (since G is finite, u can only have a finite number of neighbors). It also marks u visited, thus decreasing the number of unvisited vertices.
- Otherwise, the first action of \mathsf {DFS}(G,u) is to mark u visited, thus decreasing the number of unvisited vertices by one. Each recursive call to an unvisited neighbor \mathsf {DFS}(G,v) will be with fewer unvisited vertices, and therefore by the induction hypothesis will terminate and reduce the number of unvisited vertices further.
Remark [00ME]
- September 18, 2026
We also note that \mathsf {DFS}(G,v) terminates even if we call it on a visited vertex v, since it will proceed to call itself recursively on only the unvisited neighbors of v, so the above theorem applies to each of the recursive calls.
There are many things we could prove about DFS—indeed, DFS has a lot of nice properties that can be used for all sorts of purposes which we sadly don't have time to talk about—but the most basic one is that DFS discovers which vertices are connected and which are not.
DFS solves connectivity [00MD]
- September 18, 2026
Assuming all vertices start out unvisited, \mathsf {DFS}(G,s) ends up visiting t if and only if s and t are connected.
Proof.
- September 18, 2026
- By definition, \mathsf {DFS} only explores along edges, i.e. paths. If s and t are not connected, there is no way that \mathsf {DFS} starting from s will be able to reach t.
If s and t are connected, by definition there must be some path from s to t. Since we already know \mathsf {DFS} always terminates, we can do induction on the number of recursive calls needed for \mathsf {DFS} to complete.
Suppose the next vertex on the path from s to t is v, so there is an edge between s and v. Then either the call to \mathsf {DFS}(G,s) will make a recursive call to \mathsf {DFS}(G,v) (if v is unvisited), or else if v is already visited it means that a call to \mathsf {DFS}(G,v) already happened. In either case, our induction hypothesis tells us that the recursive call \mathsf {DFS}(G,v) will end up visiting t; hence so will the original call \mathsf {DFS}(G,s).
Algorithm DFS (version 2, with parent tree) [00M9]
- September 17, 2026
What if we want to find an explicit path from s to t? As it stands, we can't: we need more information. In particular, we need to know how we got to each vertex. We can add a parent dictionary which stores the parent of each visited vertex. Every time we visit a vertex, we record its parent, i.e. the neighbor we "came from".
Note that the resulting \mathit {parent} dictionary records a tree, representing the paths we took while exploring the graph. However, instead of the each node recording its children, each node simply records its parent. So we can easily move up the tree, but not down.
That's OK though—moving up is all we need! In order to find a path from s to t (in reverse order) we can look up \mathit {parent}[t], \mathit {parent}[\mathit {parent}[t]], and so on.
Time complexity of DFS [00MA]
- September 18, 2026
What is the time complexity of this algorithm? First of all, it matters how we represent the visited vertices. We can use a dictionary (with vertices as keys and booleans as values), or an array of booleans (if the vertices are numbered 0 \dots n-1), or a set of visited vertices. Assuming some kind of array or hash table-based structure, the operations of marking a vertex as visited or checking to see if a vertex is visited should take \Theta (1).
Now, this algorithm is recursive, and we will spend some time later in the semester talking about how to analyze recursive algorithms in general, but thankfully we can do something much simpler in this case:
- We call DFS at most once for each vertex.
- We iterate over the edges adjacent to each vertex (assume it takes O(\deg (u)) to iterate over the vertices adjacent to u). This means we look at each edge twice (once from each end).
Thus the entire algorithm takes something like O(V+E), where V is the number of vertices and E is the number of edges (formally we should write |V| and |E| but we just abbreviate them as V and E). Note that we don’t use “n”: there is nothing magical about the letter n, and in this case we prefer to use the letters V and E to denote the number of vertices and number of edges, respectively.
Note also that we can’t necessarily simplify O(V+E): E might be much less than V, or much greater. We could argue that this particular version is actually O(E) (assuming it takes \Theta (1) to initialize the data structure used to track visited vertices), but we often use a variant version that loops over all vertices and calls DFS from each unvisited vertex.
Other DFS applications [00MJ]
- September 21, 2026
There are many other applications of DFS—far too many to cover in this course! I will just list a few and let you look them up if you are interested.
- DFS can be used to find articulation points (aka cut vertices) and bridges, i.e. vertices and edges whose removal would disconnect a graph.
- DFS can be used to topologically sort a directed graph. We will learn a different algorithm for this later.
- DFS can be used to find the strongly connected components of a directed graph; this is known as Kosaraju's algorithm.
- Given a rooted tree, we can run DFS with a gobal "time" counter and label each vertex with the time we started processing it and the time we finished processing it. Then we can answer ancestry queries in \Theta (1)—to check whether vertex a is an ancestor of vertex b in the tree, just check whether b's start and end times lie within a's start and end times.