Jump to content

Depth-first search

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Jerf (talk | contribs) at 16:03, 18 March 2004. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Depth First Search (DFS) is a way of traversing or searching a Tree_(graph_theory), Tree structure, or graphs. Intuitively, you start at the root (selecting some node as the root in the graph case) and explore as far as possible along each branch before backtracking.

Formally, DFS is an uninformed search that progresses by expanding the first child node of the search tree that appears and thus going deeper and deeper until a goal state is found, or it hits a node that has no children. Then the search backtracks and starts off on the next node.

From an algorithmic point-of view, all freshly expanded nodes are placed at the front of the search queue for expansion.

  • DFS is complete - if the tree is finite, then a solution would be found if one exists.
  • DFS is optimal with a finite tree and all non-negative path costs.

Space complexity of DFS is much lower compared to BFS (Breadth-first search). It also lends itself much better to heuristic methods of choosing a likely-looking branch.

When searching large graphs that can not be fully contained in memory, DFS suffers from non-termination when the length of a path in the search tree is infinite. The simple solution of "remember which nodes I've already seen" doesn't work because there can be insufficient memory. This can be solved by maintaining an increasing limit on the depth of the tree, which is called iterative deepening depth-first search.

For the following graph:

a depth-first search starting at A, assuming that the left edges in the shown graph are chosen before right edges, and assuming the search remembers previously-visited nodes and will not repeat them (since this is a small graph), will result in the search visiting the nodes in the following order: A, B, D, F, E, C, G.

If the search did not remember previously visited nodes, but given the other conditions in the previous paragraph, the search would proceed as A, B, D, F, E, A, B, D, F, E, etc. forever, caught in the A, B, F, E cycle and never reaching C or G.