Google News
logo
Algorithm - Interview Questions
What do you understand about the DFS (Depth First Search) algorithm.
DFS or Depth First Search is a technique for traversing or exploring data structures such as trees and graphs. The algorithm starts at the root node (in the case of a graph, any random node can be used as the root node) and examines each branch as far as feasible before retracing. So the basic idea is to start at the root or any arbitrary node and mark it, then advance to the next unmarked node and repeat until there are no more unmarked nodes. After that, go back and check for any more unmarked nodes to cross. Finally, print the path's nodes. The DFS algorithm is given below :
 
Step1 : Create a recursive function that takes the node's index and a visited array as input.
Step 2 : Make the current node a visited node and print it.
Step 3 : Call the recursive function with the index of the adjacent node after traversing all nearby and unmarked nodes.
Advertisement