Depth-First Search (DFS) Is An

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data

structures. One starts at the root (selecting some arbitrary node as the root in the case
of a graph) and explores as far as possible along each branch before backtracking.

Order in which the nodes are visited


Class

Search algorithm

Data structure

Graph

Worst case
performance

for explicit graphs traversed without repetition,


graphs with branching factor b searched to depth d

for implicit

Worst case space


if entire graph is traversed without repetition, O(longest path
complexity
length searched) for implicit graphs without elimination of duplicate nodes

Example
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 visit the nodes in the
following order: A, B, D, F, E, C, G. The edges traversed in this search form a Trmaux
tree, a structure with important applications in graph theory.
Performing the same search without remembering previously visited nodes results in
visiting nodes in the order A, B, D, F, E, A, B, D, F, E, etc. forever, caught in the A, B, D,
F, E cycle and never reaching C or G. Iterative deepening is one technique to avoid this
infinite loop and would reach all nodes.

Algorithm
An algorithm for the depth first search is the same as that for breadth first search
except in the ordering of the nodes.
1.
2.
3.
4.
stack.
5.

Place the starting node s on the top of the stack.


If the stack is empty, return failure and stop.
If the element on the stack is goal node g, return success and stop. Otherwise,
Remove and expand the first element , and place the children at the top of the
Return to step 2.

ADVANTAGES OF DEPTH-FIRST SEARCH


The advantage of depth-first Search is that memory requirement is only linear with
respect to the search graph. This is in contrast with breadth-first search which requires
more space. The reason is that the algorithm only needs to store a stack of nodes on
the path from the root to the current node.
The time complexity of a depth-first Search to depth d is O(b^d) since it generates the
same set of nodes as breadth-first search, but simply in a different order. Thus
practically depth-first search is time-limited rather than space-limited.
If depth-first search finds solution without exploring much in a path, then the time and
space it takes will be very less.

You might also like