Which data structures are used in BFS and DFS algorithm?

  • In BFS algorithm, Queue data structure is used.
  • In DFS algorithm, Stack data structure is used.

Both BFS (Breadth-First Search) and DFS (Depth-First Search) algorithms can be implemented using various data structures. Here are the commonly used ones:

  1. Queue for BFS: BFS typically uses a queue data structure to keep track of the nodes to visit next. The nodes are visited in the order in which they were discovered, hence the “breadth-first” nature. This ensures that nodes at the current level are visited before moving on to the next level.
  2. Stack or Recursive Function Calls for DFS: DFS can be implemented using either a stack data structure or through recursive function calls. In the stack-based approach, you push nodes onto the stack as you visit them, and then pop them off the stack to backtrack when necessary. In the recursive approach, each recursive call effectively serves as a frame on the call stack, preserving the path taken from the root to the current node.

So, the correct answer would be:

  • Queue for BFS
  • Stack or Recursive Function Calls for DFS