Print the DFS traversal step | Python3 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
N = 1000 NEW_LINE adj = [ [ ] for i in range ( N ) ] NEW_LINE def dfsUtil ( u , node , visited , road_used , parent , it ) : NEW_LINE INDENT c = 0 NEW_LINE for i in range ( node ) : NEW_LINE INDENT if ( visited [ i ] ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( c == node ) : NEW_LINE INDENT return NEW_LINE DEDENT visited [ u ] = True NEW_LINE road_used . append ( [ parent , u ] ) NEW_LINE print ( u , end = " ▁ " ) NEW_LINE for x in adj [ u ] : NEW_LINE INDENT if ( not visited [ x ] ) : NEW_LINE INDENT dfsUtil ( x , node , visited , road_used , u , it + 1 ) NEW_LINE DEDENT DEDENT for y in road_used : NEW_LINE INDENT if ( y [ 1 ] == u ) : NEW_LINE INDENT dfsUtil ( y [ 0 ] , node , visited , road_used , u , it + 1 ) NEW_LINE DEDENT DEDENT DEDENT def dfs ( node ) : NEW_LINE INDENT visited = [ False for i in range ( node ) ] NEW_LINE road_used = [ ] NEW_LINE for i in range ( node ) : NEW_LINE INDENT visited [ i ] = False NEW_LINE DEDENT dfsUtil ( 0 , node , visited , road_used , - 1 , 0 ) NEW_LINE DEDENT def insertEdge ( u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT node = 11 NEW_LINE edge = 13 NEW_LINE insertEdge ( 0 , 1 ) NEW_LINE insertEdge ( 0 , 2 ) NEW_LINE insertEdge ( 1 , 5 ) NEW_LINE insertEdge ( 1 , 6 ) NEW_LINE insertEdge ( 2 , 4 ) NEW_LINE insertEdge ( 2 , 9 ) NEW_LINE insertEdge ( 6 , 7 ) NEW_LINE insertEdge ( 6 , 8 ) NEW_LINE insertEdge ( 7 , 8 ) NEW_LINE insertEdge ( 2 , 3 ) NEW_LINE insertEdge ( 3 , 9 ) NEW_LINE insertEdge ( 3 , 10 ) NEW_LINE insertEdge ( 9 , 10 ) NEW_LINE dfs ( node ) NEW_LINE DEDENT