...

/

Graph Traversal - Depth-First Search

Graph Traversal - Depth-First Search

Learn the Depth-First traversal technique to traverse graphs.

We'll cover the following...

Depth-First Search approach

The Depth-First Search (DFS) algorithm is a recursive algorithm that uses the idea of Backtracking. It involves exhaustive searches of all the nodes by going ahead if possible, and if not, by backtracking. Here, the word backtrack means that when you are moving forward and there are no more nodes along the current path, you move backward on the same path to find nodes to traverse. All the nodes will be visited on the current path till all the un-visited nodes have been traversed after which the next path will be selected.

This recursive nature of Depth-First Search can be implemented using stacks. The basic idea is as follows:

  • Pick a starting node and push all its adjacent nodes into a stack.
  • Pop a node from the stack to select the next node to visit and push all its adjacent nodes into a stack.
  • Repeat this process until the stack is empty. However, ensure that the
...