Are DFS trees unique

algorithmscomputer sciencegraph theoryoptimization

Suppose you have no priority on the way you decide which vertices to explore in your DFS algorithm (so that any neighbor is equally likely to be visited in every iteration). Then, is it true that the DFS-tree from a root is not unique i.e. the DFS algorithm can output different DFS-trees for different runs? (for one example, consider a simple, undirected 5-cycle with exactly one additional edge).

If my claim is true, then I also want to ask, how do people usually run DFS? Do they assign priority to some paths other than others? Do they want the same output over all runs, given the same graph and starting vertex? This latter condition seems desirable, because I cannot imagine why anyone might want an algorithm whose output is not identical across trials?

Best Answer

Yes, DFS trees are not unique - your example serves as enough. You can consider some cycle graph and notice there are at least two ways to traverse the cycle using DFS, starting at a given vertex.

When you use a linked list adjacency structure, the neighbors are automatically assigned priority when you add their edges to the graph. So the DFS will just use these priorities (i.e. select the next neighbor of the vertex) and give the same representation every time. In general this would give different traversals depending on the order edges are added.

Someone using an adjacency matrix would have to do DFS based on the order the vertices are assigned (you have to label each vertex with a number).