VOOZH about

URL: https://www.geeksforgeeks.org/dsa/iterative-depth-first-traversal/

⇱ Iterative Depth First Traversal of Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Iterative Depth First Traversal of Graph

Last Updated : 23 Jul, 2025

Given a directed Graph, the task is to perform Depth First Search of the given graph.

Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list.

Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick vertices as per the insertion order.

Input: adj = [[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]
👁 Input_undirected_Graph

Output: [0 1 2 3 4]
Explanation: The source vertex s is 0. We visit it first, then we visit an adjacent.
Start at 0: Mark as visited. Output: 0
Move to 1: Mark as visited. Output: 1
Move to 2: Mark as visited. Output: 2
Move to 3: Mark as visited. Output: 3 (backtrack to 2)
Move to 4: Mark as visited. Output: 4 (backtrack to 2, then backtrack to 1, then to 0)

Not that there can be more than one DFS Traversals of a Graph. For example, after 1, we may pick adjacent 2 instead of 0 and get a different DFS. Here we pick in the insertion order.

Input: [[2,3,1], [0], [0,4], [0], [2]]

👁 Input_undirected_Graph2

Output: [0 2 4 3 1]
Explanation: DFS Steps:

Start at 0: Mark as visited. Output: 0
Move to 2: Mark as visited. Output: 2
Move to 4: Mark as visited. Output: 4 (backtrack to 2, then backtrack to 0)
Move to 3: Mark as visited. Output: 3 (backtrack to 0)
Move to 1: Mark as visited. Output: 1 (backtrack to 0)

The recursive implementation of DFS is already discussed: Depth First Search or DFS for a Graph.

Iterative DFS for Connected Graph - O(V + E) time and O(V) space

The idea is to fist push the given source into the stack. Then keep popping items from the stack while stack has items. Once we pop an item, we add it to the result and then push all its adjacent into the stack in reverse order. Please note that the last added item is going to be removed first.

Step by step approach:

  1. Initialize an empty stack, and push node 0 into it.
  2. Pop a vertex, mark it as visited only if not already visited.
  3. Add the visited vertex to the result collection.
  4. Push all unvisited adjacent vertices to the stack in reverse order.

Output
0 1 2 3 
👁 Iterative Depth First Traversal of Graph 1

Iterative DFS for Disconnected Graph - O(V + E) time and O(V) space

The above solution works only for connected graph. In this approach, the idea is to ensure that all nodes are visited. If a node is unvisited, start DFS from this node.


Output
0 1 2 3 
Comment
Article Tags:
Article Tags: