DFS for a n | JAVA Code For DFS for a n - ary tree ( acyclic graph ) represented as adjacency list ; DFS on tree ; Printing traversed node ; Traversing adjacent edges ; Not traversing the parent node ; Driver program to test above function ; Number of nodes ; Adjacency list ; Designing the tree ; Function call
import java . util . * ; class GFG { public static void dfs ( LinkedList < Integer > list [ ] , int node , int arrival ) { System . out . println ( node ) ; for ( int i = 0 ; i < list [ node ] . size ( ) ; i ++ ) { if ( list [ node ] . get ( i ) != arrival ) dfs ( list , list [ node ] . get ( i ) , node ) ; } } public static void main ( String [ ] args ) { int nodes = 5 ; LinkedList < Integer > list [ ] = new LinkedList [ nodes + 1 ] ; for ( int i = 0 ; i < list . length ; i ++ ) { list [ i ] = new LinkedList < Integer > ( ) ; } list [ 1 ] . add ( 2 ) ; list [ 2 ] . add ( 1 ) ; list [ 1 ] . add ( 3 ) ; list [ 3 ] . add ( 1 ) ; list [ 2 ] . add ( 4 ) ; list [ 4 ] . add ( 2 ) ; list [ 3 ] . add ( 5 ) ; list [ 5 ] . add ( 3 ) ; dfs ( list , 1 , 0 ) ; } }