DFS for a n | C # 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
using System ; using System . Collections . Generic ; public class GFG { public static void dfs ( List < int > [ ] list , int node , int arrival ) { Console . WriteLine ( node ) ; for ( int i = 0 ; i < list [ node ] . Count ; i ++ ) { if ( list [ node ] [ i ] != arrival ) dfs ( list , list [ node ] [ i ] , node ) ; } } public static void Main ( String [ ] args ) { int nodes = 5 ; List < int > [ ] list = new List < int > [ nodes + 1 ] ; for ( int i = 0 ; i < list . Length ; i ++ ) { list [ i ] = new List < int > ( ) ; } 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 ) ; } }