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
By strong induction on the number of unvisited vertices.
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.
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.