Print the DFS traversal step | Java program to print the complete DFS - traversal of graph using back - tracking ; Function to print the complete DFS - traversal ; Check if all th node is visited or not and count unvisited nodes ; If all the node is visited return ; ; Mark not visited node as visited ; Track the current edge ; Print the node ; Check for not visited node and proceed with it . ; call the DFs function if not visited ; Backtrack through the last visited nodes ; Function to call the DFS function which prints the DFS - traversal stepwise ; Create a array of visited node ; Vector to track last visited road ; Initialize all the node with false ; call the function ; Function to insert edges in Graph ; Driver Code ; number of nodes and edges in the graph ; Function call to create the graph ; Call the function to print
import java . io . * ; import java . util . * ; class GFG { static int N = 1000 ; static ArrayList < ArrayList < Integer > > adj = new ArrayList < ArrayList < Integer > > ( ) ; static void dfsUtil ( int u , int node , boolean visited [ ] , ArrayList < ArrayList < Integer > > road_used , int parent , int it ) { int c = 0 ; for ( int i = 0 ; i < node ; i ++ ) if ( visited [ i ] ) c ++ ; if ( c == node ) return ; visited [ u ] = true ; road_used . add ( new ArrayList < Integer > ( Arrays . asList ( parent , u ) ) ) ; System . out . print ( u + " ▁ " ) ; for ( int x : adj . get ( u ) ) { if ( ! visited [ x ] ) { dfsUtil ( x , node , visited , road_used , u , it + 1 ) ; } } for ( int y = 0 ; y < road_used . size ( ) ; y ++ ) { if ( road_used . get ( y ) . get ( 1 ) == u ) { dfsUtil ( road_used . get ( y ) . get ( 0 ) , node , visited , road_used , u , it + 1 ) ; } } } static void dfs ( int node ) { boolean [ ] visited = new boolean [ node ] ; ArrayList < ArrayList < Integer > > road_used = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < node ; i ++ ) { visited [ i ] = false ; } dfsUtil ( 0 , node , visited , road_used , - 1 , 0 ) ; } static void insertEdge ( int u , int v ) { adj . get ( u ) . add ( v ) ; adj . get ( v ) . add ( u ) ; } public static void main ( String [ ] args ) { int node = 11 , edge = 13 ; for ( int i = 0 ; i < N ; i ++ ) { adj . add ( new ArrayList < Integer > ( ) ) ; } insertEdge ( 0 , 1 ) ; insertEdge ( 0 , 2 ) ; insertEdge ( 1 , 5 ) ; insertEdge ( 1 , 6 ) ; insertEdge ( 2 , 4 ) ; insertEdge ( 2 , 9 ) ; insertEdge ( 6 , 7 ) ; insertEdge ( 6 , 8 ) ; insertEdge ( 7 , 8 ) ; insertEdge ( 2 , 3 ) ; insertEdge ( 3 , 9 ) ; insertEdge ( 3 , 10 ) ; insertEdge ( 9 , 10 ) ; dfs ( node ) ; } }