Iterative Depth First Traversal of Graph
- Difficulty Level : Easy
- Last Updated : 26 Nov, 2021
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array.
Example:
Input: n = 4, e = 6
0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3
Output: DFS from vertex 1 : 1 2 0 3
Explanation:
DFS Diagram:
Input: n = 4, e = 6
2 -> 0, 0 -> 2, 1 -> 2, 0 -> 1, 3 -> 3, 1 -> 3
Output: DFS from vertex 2 : 2 0 1 3
Explanation:
DFS Diagram:
The recursive implementation of DFS is already discussed: previous post.
Solution:
- Approach: Depth-first search is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally print the nodes in the path.
The only difference between iterative DFS and recursive DFS is that the recursive stack is replaced by a stack of nodes.- Algorithm:
- Created a stack of nodes and visited array.
- Insert the root in the stack.
- Run a loop till the stack is not empty.
- Pop the element from the stack and print the element.
- For every adjacent and unvisited node of current node, mark the node and insert it in the stack.
- Implementation of Iterative DFS: This is similar to BFS, the only difference is queue is replaced by stack.
C++
// An Iterative C++ program to do DFS traversal from// a given source vertex. DFS(int s) traverses vertices// reachable from s.#include<bits/stdc++.h>usingnamespacestd;// This class represents a directed graph using adjacency// list representationclassGraph{intV;// No. of verticeslist<int> *adj;// adjacency listspublic:Graph(intV);// ConstructorvoidaddEdge(intv,intw);// to add an edge to graphvoidDFS(ints);// prints all vertices in DFS manner// from a given source.};Graph::Graph(intV){this->V = V;adj =newlist<int>[V];}voidGraph::addEdge(intv,intw){adj[v].push_back(w);// Add w to v’s list.}// prints all not yet visited vertices reachable from svoidGraph::DFS(ints){// Initially mark all vertices as not visitedvector<bool> visited(V,false);// Create a stack for DFSstack<int> stack;// Push the current source node.stack.push(s);while(!stack.empty()){// Pop a vertex from stack and print itints = stack.top();stack.pop();// Stack may contain same vertex twice. So// we need to print the popped item only// if it is not visited.if(!visited[s]){cout << s <<" ";visited[s] =true;}// Get all adjacent vertices of the popped vertex s// If a adjacent has not been visited, then push it// to the stack.for(autoi = adj[s].begin(); i != adj[s].end(); ++i)if(!visited[*i])stack.push(*i);}}// Driver program to test methods of graph classintmain(){Graph g(5);// Total 5 vertices in graphg.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(1, 4);cout <<"Following is Depth First Traversal\n";g.DFS(0);return0;}Java
//An Iterative Java program to do DFS traversal from//a given source vertex. DFS(int s) traverses vertices//reachable from s.importjava.util.*;publicclassGFG{// This class represents a directed graph using adjacency// list representationstaticclassGraph{intV;//Number of VerticesLinkedList<Integer>[] adj;// adjacency lists//ConstructorGraph(intV){this.V = V;adj =newLinkedList[V];for(inti =0; i < adj.length; i++)adj[i] =newLinkedList<Integer>();}//To add an edge to graphvoidaddEdge(intv,intw){adj[v].add(w);// Add w to v’s list.}// prints all not yet visited vertices reachable from svoidDFS(ints){// Initially mark all vertices as not visitedVector<Boolean> visited =newVector<Boolean>(V);for(inti =0; i < V; i++)visited.add(false);// Create a stack for DFSStack<Integer> stack =newStack<>();// Push the current source nodestack.push(s);while(stack.empty() ==false){// Pop a vertex from stack and print its = stack.peek();stack.pop();// Stack may contain same vertex twice. So// we need to print the popped item only// if it is not visited.if(visited.get(s) ==false){System.out.print(s +" ");visited.set(s,true);}// Get all adjacent vertices of the popped vertex s// If a adjacent has not been visited, then push it// to the stack.Iterator<Integer> itr = adj[s].iterator();while(itr.hasNext()){intv = itr.next();if(!visited.get(v))stack.push(v);}}}}// Driver program to test methods of graph classpublicstaticvoidmain(String[] args){// Total 5 vertices in graphGraph g =newGraph(5);g.addEdge(1,0);g.addEdge(0,2);g.addEdge(2,1);g.addEdge(0,3);g.addEdge(1,4);System.out.println("Following is the Depth First Traversal");g.DFS(0);}}Python3
# An Iterative Python program to do DFS traversal from# a given source vertex. DFS(int s) traverses vertices# reachable from s.# This class represents a directed graph using adjacency# list representationclassGraph:def__init__(self,V):# Constructorself.V=V# No. of verticesself.adj=[[]foriinrange(V)]# adjacency listsdefaddEdge(self,v, w):# to add an edge to graphself.adj[v].append(w)# Add w to v’s list.# prints all not yet visited vertices reachable from sdefDFS(self,s):# prints all vertices in DFS manner from a given source.# Initially mark all vertices as not visitedvisited=[Falseforiinrange(self.V)]# Create a stack for DFSstack=[]# Push the current source node.stack.append(s)while(len(stack)):# Pop a vertex from stack and print its=stack[-1]stack.pop()# Stack may contain same vertex twice. So# we need to print the popped item only# if it is not visited.if(notvisited[s]):(s,end=' ')visited[s]=True# Get all adjacent vertices of the popped vertex s# If a adjacent has not been visited, then push it# to the stack.fornodeinself.adj[s]:if(notvisited[node]):stack.append(node)# Driver program to test methods of graph classg=Graph(5);# Total 5 vertices in graphg.addEdge(1,0);g.addEdge(0,2);g.addEdge(2,1);g.addEdge(0,3);g.addEdge(1,4);("Following is Depth First Traversal")g.DFS(0)# This code is contributed by ankush_953C#
// An Iterative C# program to do DFS traversal from// a given source vertex. DFS(int s) traverses vertices// reachable from s.usingSystem;usingSystem.Collections.Generic;classGFG{// This class represents a directed graph using adjacency// list representationpublicclassGraph{publicintV;// Number of VerticespublicLinkedList<int>[] adj;// adjacency lists// ConstructorpublicGraph(intV){this.V = V;adj =newLinkedList<int>[V];for(inti = 0; i < adj.Length; i++)adj[i] =newLinkedList<int>();}// To add an edge to graphpublicvoidaddEdge(intv,intw){adj[v].AddLast(w);// Add w to v’s list.}// prints all not yet visited vertices reachable from spublicvoidDFS(ints){// Initially mark all vertices as not visitedBoolean []visited =newBoolean[V];// Create a stack for DFSStack<int> stack =newStack<int>();// Push the current source nodestack.Push(s);while(stack.Count > 0){// Pop a vertex from stack and print its = stack.Peek();stack.Pop();// Stack may contain same vertex twice. So// we need to print the popped item only// if it is not visited.if(visited[s] ==false){Console.Write(s +" ");visited[s] =true;}// Get all adjacent vertices of the popped vertex s// If a adjacent has not been visited, then push it// to the stack.foreach(intvinadj[s]){if(!visited[v])stack.Push(v);}}}}// Driver codepublicstaticvoidMain(String []args){// Total 5 vertices in graphGraph g =newGraph(5);g.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(1, 4);Console.Write("Following is the Depth First Traversal\n");g.DFS(0);}}// This code is contributed by Arnasb KunduJavascript
<script>// An Iterative Javascript program to// do DFS traversal from a given source// vertex. DFS(int s) traverses vertices// reachable from s.// This class represents a directed graph// using adjacency list representationclass Graph{constructor(V){this.V = V;this.adj =newArray(V);for(let i = 0; i <this.adj.length; i++)this.adj[i] = [];}// To add an edge to graphaddEdge(v, w){// Add w to v’s list.this.adj[v].push(w);}// Prints all not yet visited// vertices reachable from sDFS(s){// Initially mark all vertices as not visitedlet visited = [];for(let i = 0; i <this.V; i++)visited.push(false);// Create a stack for DFSlet stack = [];// Push the current source nodestack.push(s);while(stack.length != 0){// Pop a vertex from stack and print its = stack.pop();// Stack may contain same vertex twice. So// we need to print the popped item only// if it is not visited.if(visited[s] ==false){document.write(s +" ");visited[s] =true;}// Get all adjacent vertices of the// popped vertex s. If a adjacent has// not been visited, then push it// to the stack.for(let node = 0;node <this.adj[s].length;node++){if(!visited[this.adj[s][node]])stack.push(this.adj[s][node])}}}}// Driver code// Total 5 vertices in graphlet g =newGraph(5);g.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(1, 4);document.write("Following is the Depth "+"First Traversal<br>");g.DFS(0);// This code is contributed by rag2127</script>Output:
Following is Depth First Traversal 0 3 2 1 4
- Complexity Analysis:
- Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.
- Space Complexity: O(V). Since an extra visited array is needed of size V.
Modification of the above Solution: Note that the above implementation prints only vertices that are reachable from a given vertex. For example, if the edges 0-3 and 0-2 are removed, then the above program would only print 0. To print all vertices of a graph, call DFS for every unvisited vertex.
Implementation:
C++
// An Iterative C++ program to do DFS traversal from// a given source vertex. DFS(int s) traverses vertices// reachable from s.#include<bits/stdc++.h>usingnamespacestd;// This class represents a directed graph using adjacency// list representationclassGraph{intV;// No. of verticeslist<int> *adj;// adjacency listspublic:Graph(intV);// ConstructorvoidaddEdge(intv,intw);// to add an edge to graphvoidDFS();// prints all vertices in DFS manner// prints all not yet visited vertices reachable from svoidDFSUtil(ints, vector<bool> &visited;);};Graph::Graph(intV){this->V = V;adj =newlist<int>[V];}voidGraph::addEdge(intv,intw){adj[v].push_back(w);// Add w to v’s list.}// prints all not yet visited vertices reachable from svoidGraph::DFSUtil(ints, vector<bool> &visited;){// Create a stack for DFSstack<int> stack;// Push the current source node.stack.push(s);while(!stack.empty()){// Pop a vertex from stack and print itints = stack.top();stack.pop();// Stack may contain same vertex twice. So// we need to print the popped item only// if it is not visited.if(!visited[s]){cout << s <<" ";visited[s] =true;}// Get all adjacent vertices of the popped vertex s// If a adjacent has not been visited, then push it// to the stack.for(autoi = adj[s].begin(); i != adj[s].end(); ++i)if(!visited[*i])stack.push(*i);}}// prints all vertices in DFS mannervoidGraph::DFS(){// Mark all the vertices as not visitedvector<bool> visited(V,false);for(inti = 0; i < V; i++)if(!visited[i])DFSUtil(i, visited);}// Driver program to test methods of graph classintmain(){Graph g(5);// Total 5 vertices in graphg.addEdge(1, 0);g.addEdge(2, 1);g.addEdge(3, 4);g.addEdge(4, 0);cout <<"Following is Depth First Traversal\n";g.DFS();return0;}Java
//An Iterative Java program to do DFS traversal from//a given source vertex. DFS() traverses vertices//reachable from s.importjava.util.*;publicclassGFG{// This class represents a directed graph using adjacency// list representationstaticclassGraph{intV;//Number of VerticesLinkedList<Integer>[] adj;// adjacency lists//ConstructorGraph(intV){this.V = V;adj =newLinkedList[V];for(inti =0; i < adj.length; i++)adj[i] =newLinkedList<Integer>();}//To add an edge to graphvoidaddEdge(intv,intw){adj[v].add(w);// Add w to v’s list.}// prints all not yet visited vertices reachable from svoidDFSUtil(ints, Vector<Boolean> visited){// Create a stack for DFSStack<Integer> stack =newStack<>();// Push the current source nodestack.push(s);while(stack.empty() ==false){// Pop a vertex from stack and print its = stack.peek();stack.pop();// Stack may contain same vertex twice. So// we need to print the popped item only// if it is not visited.if(visited.get(s) ==false){System.out.print(s +" ");visited.set(s,true);}// Get all adjacent vertices of the popped vertex s// If a adjacent has not been visited, then push it// to the stack.Iterator<Integer> itr = adj[s].iterator();while(itr.hasNext()){intv = itr.next();if(!visited.get(v))stack.push(v);}}}// prints all vertices in DFS mannervoidDFS(){Vector<Boolean> visited =newVector<Boolean>(V);// Mark all the vertices as not visitedfor(inti =0; i < V; i++)visited.add(false);for(inti =0; i < V; i++)if(!visited.get(i))DFSUtil(i, visited);}}// Driver program to test methods of graph classpublicstaticvoidmain(String[] args){Graph g =newGraph(5);g.addEdge(1,0);g.addEdge(2,1);g.addEdge(3,4);g.addEdge(4,0);System.out.println("Following is Depth First Traversal");g.DFS();}}Python3
# An Iterative Python3 program to do DFS# traversal from a given source vertex.# DFS(s) traverses vertices reachable from s.classGraph:def__init__(self, V):self.V=Vself.adj=[[]foriinrange(V)]defaddEdge(self, v, w):self.adj[v].append(w)# Add w to v’s list.# prints all not yet visited vertices# reachable from sdefDFSUtil(self, s, visited):# Create a stack for DFSstack=[]# Push the current source node.stack.append(s)while(len(stack) !=0):# Pop a vertex from stack and print its=stack.pop()# Stack may contain same vertex twice.# So we need to print the popped item only# if it is not visited.if(notvisited[s]):(s, end=" ")visited[s]=True# Get all adjacent vertices of the# popped vertex s. If a adjacent has not# been visited, then push it to the stack.i=0whilei <len(self.adj[s]):if(notvisited[self.adj[s][i]]):stack.append(self.adj[s][i])i+=1# prints all vertices in DFS mannerdefDFS(self):# Mark all the vertices as not visitedvisited=[False]*self.Vforiinrange(self.V):if(notvisited[i]):self.DFSUtil(i, visited)# Driver Codeif__name__=='__main__':g=Graph(5)# Total 5 vertices in graphg.addEdge(1,0)g.addEdge(2,1)g.addEdge(3,4)g.addEdge(4,0)("Following is Depth First Traversal")g.DFS()# This code is contributed by PranchalKC#
// An Iterative C# program to do DFS traversal from// a given source vertex. DFS() traverses vertices// reachable from s.usingSystem;usingSystem.Collections.Generic;classGFG{// This class represents a directed graph using adjacency// list representationclassGraph{publicintV;// Number of VerticespublicList<int>[] adj;// adjacency lists// ConstructorpublicGraph(intV){this.V = V;adj =newList<int>[V];for(inti = 0; i < adj.Length; i++)adj[i] =newList<int>();}// To add an edge to graphpublicvoidaddEdge(intv,intw){adj[v].Add(w);// Add w to v’s list.}// prints all not yet visited vertices reachable from spublicvoidDFSUtil(ints, List<Boolean> visited){// Create a stack for DFSStack<int> stack =newStack<int>();// Push the current source nodestack.Push(s);while(stack.Count != 0){// Pop a vertex from stack and print its = stack.Peek();stack.Pop();// Stack may contain same vertex twice. So// we need to print the popped item only// if it is not visited.if(visited[s] ==false){Console.Write(s +" ");visited[s] =true;}// Get all adjacent vertices of the popped vertex s// If a adjacent has not been visited, then push it// to the stack.foreach(intitrinadj[s]){intv = itr;if(!visited[v])stack.Push(v);}}}// prints all vertices in DFS mannerpublicvoidDFS(){List<Boolean> visited =newList<Boolean>(V);// Mark all the vertices as not visitedfor(inti = 0; i < V; i++)visited.Add(false);for(inti = 0; i < V; i++)if(!visited[i])DFSUtil(i, visited);}}// Driver codepublicstaticvoidMain(String[] args){Graph g =newGraph(5);g.addEdge(1, 0);g.addEdge(2, 1);g.addEdge(3, 4);g.addEdge(4, 0);Console.WriteLine("Following is Depth First Traversal");g.DFS();}}// This code is contributed by 29AjayKumarJavascript
<script>//An Iterative Javascript program to do DFS traversal from//a given source vertex. DFS() traverses vertices//reachable from s.// This class represents a directed graph using adjacency// list representationclass Graph{//Constructorconstructor(V){this.V=V;this.adj =newArray(V);for(let i = 0; i <this.adj.length; i++)this.adj[i] = [];}//To add an edge to graphaddEdge(v,w){this.adj[v].push(w);// Add w to v’s list.}// prints all not yet visited vertices reachable from sDFSUtil(s,visited){// Create a stack for DFSlet stack = [];// Push the current source nodestack.push(s);while(stack.length != 0){// Pop a vertex from stack and print its = stack.pop();// Stack may contain same vertex twice. So// we need to print the popped item only// if it is not visited.if(visited[s] ==false){document.write(s +" ");visited[s] =true;}// Get all adjacent vertices of the popped vertex s// If a adjacent has not been visited, then push it// to the stack.for(let itr=0;itr<this.adj[s].length;itr++){let v =this.adj[s][itr];if(!visited[v])stack.push(v);}}}// prints all vertices in DFS mannerDFS(){let visited = []// Mark all the vertices as not visitedfor(let i = 0; i <this.V; i++)visited.push(false);for(let i = 0; i <this.V; i++)if(!visited[i])this.DFSUtil(i, visited);}}// Driver program to test methods of graph classlet g =newGraph(5);g.addEdge(1, 0);g.addEdge(2, 1);g.addEdge(3, 4);g.addEdge(4, 0);document.write("Following is Depth First Traversal<br>");g.DFS();// This code is contributed by avanitrachhadiya2155</script>Output:
Following is Depth First Traversal 0 1 2 3 4Like recursive traversal, the time complexity of iterative implementation is O(V + E).
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
My Personal Notes arrow_drop_upRecommended ArticlesPage :Article Contributed By :Improved By :






