Method (Depth First Search)
Depth First Search (DFS) keeps a list of vertices connected so far in order. It connects a new vertex to the most recent possible option.
It also allows us to create a spanning tree of a graph. For example,
graph LR; 1((1)) o--o 2((2)); 1((1)) o--o 3((3)); 2((2)) o--o 3((3)); 1((1)) o--o 7((7)); 2((2)) o--o 6((6)); 3((3)) o--o 4((4)); 3((3)) o--o 5((5)); 3((3)) o--o 7((7)); 4((4)) o--o 5((5)); 8((8)) o--o 4((4)); 4((4)) o--o 7((7)); 8((8)) o--o 5((5)); 5((5)) o--o 6((6)); 6((6)) o--o 7((7));
which, follows . But then it needs to backtrack since we cannot reach . Thus, we go from and then . This gives a new tree:
graph LR; 1((1)) o--o 2((2)); 2 o--o 3((3)); 3 o--o 4((4)); 4 o--o 5((5)); 5 o--o 8((8)); 5 o--o 6((6)); 6 o--o 7((7));
In general, DFS trees create long skinny graphs.
Lemma (DFS Trees Connect Ancestors)
In a DFS tree, all other edges of connect ancestors.
Proof: Instead of an ancestor, you can have a cousin:
graph LR; c((c)) o--o a((a)); c o--o b((b)); a o-.e.-o b;
where is some common ancestor and some edge that connects and . But this cannot happen with DFS. This is because we will not connect to anything new until all of ‘s neighbors have been added. So we must explore once we finish exploring ‘s children.