On Depth First Search
On Depth First Search
always exploring from the most recently discovered vertex and backtracking only when necessary (like exploring a maze).
While DFS ultimately visits exactly the same set of nodes as BFS, it typically does so in a
very different order; it probes its way down long paths, potentially getting very far from s,
before backing up to try nearer unexplored nodes.
The Depth First Search Algorithm
DFS is depth first search, so you have to traverse a whole branch of tree then
you can traverse the adjacent nodes. So for keep tracking on the current node
it requires last in first out approach which can be implemented by stack, after it
reaches the depth of a node then all the nodes will be popped out of stack.
Next it searches for adjacent nodes which are not visited yet. If it was
implemented with queue i.e. first in first out approach we could not reach to
the depth, before that it would dequeue the current node.
A stack maintains a list of objects, and you can add an object to the beginning of the list
(a “push”) or remove one from the beginning of the list (a “pop”) in constant time.
Recursive and Iterative
Implementation
Depth First Search
The Depth First Search Algorithm
DFS is also a particular implementation of the generic component-growing
algorithm. It is most easily described in recursive form: we can invoke DFS
from any starting point but maintain global knowledge of which nodes
have already been explored.
The Depth First Search Algorithm
Iterative Implementation
Since the STACK is now empty, the depth-first search of G starting at node
H is complete and the nodes which were printed are:
H, I, F, C, G, B, E
These are the nodes which are reachable from the node H.