Print the DFS traversal step | Javascript 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 ; number of nodes and edges in the graph ; Function call to create the graph ; Call the function to print
let N = 1000 ; let adj = [ ] ; function dfsUtil ( u , node , visited , road_used , parent , it ) { let c = 0 ; for ( let i = 0 ; i < node ; i ++ ) if ( visited [ i ] ) c ++ ; if ( c == node ) return ; visited [ u ] = true ; road_used . push ( [ parent , u ] ) ; document . write ( u + " " ) ; for ( let x = 0 ; x < adj [ u ] . length ; x ++ ) { if ( ! visited [ adj [ u ] [ x ] ] ) { dfsUtil ( adj [ u ] [ x ] , node , visited , road_used , u , it + 1 ) ; } } for ( let y = 0 ; y < road_used . length ; y ++ ) { if ( road_used [ y ] [ 1 ] == u ) { dfsUtil ( road_used [ y ] [ 0 ] , node , visited , road_used , u , it + 1 ) ; } } } function dfs ( node ) { let visited = new Array ( node ) ; let road_used = [ ] ; for ( let i = 0 ; i < node ; i ++ ) { visited [ i ] = false ; } dfsUtil ( 0 , node , visited , road_used , - 1 , 0 ) ; } function insertEdge ( u , v ) { adj [ u ] . push ( v ) ; adj [ v ] . push ( u ) ; } let node = 11 , edge = 13 ; for ( let i = 0 ; i < N ; i ++ ) { adj . push ( [ ] ) ; } 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 ) ; 9