Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)

Last Updated : 23 Jul, 2025

There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons.

  1. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first few subtrees explored by DFS, then DFS reaches that node very late. Also, DFS may not find shortest path to a node (in terms of number of edges).
  2. BFS goes level by level, but requires more space. The space required by DFS is O(d) where d is depth of tree, but space required by BFS is O(n) where n is number of nodes in tree (Why? Note that the last level of tree can have around n/2 nodes and second last level n/4 nodes and in BFS we need to have every level one by one in queue).

IDDFS combines depth-first search's space-efficiency and breadth-first search's fast search (for nodes closer to root). 

How does IDDFS work? 
IDDFS calls DFS for different depths starting from an initial value. In every call, DFS is restricted from going beyond given depth. So basically we do DFS in a BFS fashion. 

Algorithm:

// Returns true if target is reachable from
// src within max_depth
bool IDDFS(src, target, max_depth)
for limit from 0 to max_depth
if DLS(src, target, limit) == true
return true
return false

bool DLS(src, target, limit)
if (src == target)
return true;

// If reached the maximum depth,
// stop recursing.
if (limit <= 0)
return false;

foreach adjacent i of src
if DLS(i, target, limit-1)
return true

return false

An important thing to note is, we visit top level nodes multiple times. The last (or max depth) level is visited once, second last level is visited twice, and so on. It may seem expensive, but it turns out to be not so costly, since in a tree most of the nodes are in the bottom level. So it does not matter much if the upper levels are visited multiple times. Below is implementation of above algorithm 

C++
// C++ program to search if a target node is reachable from 
// a source with given max depth. 
#include<bits/stdc++.h> 
using namespace std; 
  
// Graph class represents a directed graph using adjacency 
// list representation. 
class Graph 
{ 
    int V;    // No. of vertices 
  
    // Pointer to an array containing 
    // adjacency lists 
    list<int> *adj; 
  
    // A function used by IDDFS 
    bool DLS(int v, int target, int limit); 
  
public: 
    Graph(int V);   // Constructor 
    void addEdge(int v, int w); 
  
    // IDDFS traversal of the vertices reachable from v 
    bool IDDFS(int v, int target, int max_depth);