text: Find triplet such that number of nodes connecting these triplets is maximum | C # implementation of the approach ; To store the required nodes ; Parent array to retrace the nodes ; Visited array to prevent DFS in direction on Diameter path ; DFS function to find the startnode ; DFS function to find the endnode of diameter and maintain the parent array ; DFS function to find the end node of the Longest Branch to Diameter ; Function to find the required nodes ; To find start node of diameter ; To find end node of diameter ; x is the end node of diameter ; Mark all the nodes on diameter using back tracking ; Find the end node of longest branch to diameter ; Driver code
code: using System ; using System . Collections . Generic ; class GFG { static int MAX = 100005 ; static List < List < int > > adjacent = new List < List < int > > ( ) ; static bool [ ] visited = new bool [ MAX ] ; static int startnode , endnode , thirdnode ; static int maxi = - 1 , N ; static int [ ] parent = new int [ MAX ] ; static bool [ ] vis = new bool [ MAX ] ; static void dfs ( int u , int count ) { visited [ u ] = true ; int temp = 0 ; for ( int i = 0 ; i < adjacent [ u ] . Count ; i ++ ) { if ( ! visited [ adjacent [ u ] [ i ] ] ) { temp ++ ; dfs ( adjacent [ u ] [ i ] , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; startnode = u ; } } } static void dfs1 ( int u , int count ) { visited [ u ] = true ; int temp = 0 ; for ( int i = 0 ; i < adjacent [ u ] . Count ; i ++ ) { if ( ! visited [ adjacent [ u ] [ i ] ] ) { temp ++ ; parent [ adjacent [ u ] [ i ] ] = u ; dfs1 ( adjacent [ u ] [ i ] , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; endnode = u ; } } } static void dfs2 ( int u , int count ) { visited [ u ] = true ; int temp = 0 ; for ( int i = 0 ; i < adjacent [ u ] . Count ; i ++ ) { if ( ! visited [ adjacent [ u ] [ i ] ] && ! vis [ adjacent [ u ] [ i ] ] ) { temp ++ ; dfs2 ( adjacent [ u ] [ i ] , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; thirdnode = u ; } } } static void findNodes ( ) { dfs ( 1 , 0 ) ; for ( int i = 0 ; i <= N ; i ++ ) visited [ i ] = false ; maxi = - 1 ; dfs1 ( startnode , 0 ) ; for ( int i = 0 ; i <= N ; i ++ ) visited [ i ] = false ; int x = endnode ; vis [ startnode ] = true ; while ( x != startnode ) { vis [ x ] = true ; x = parent [ x ] ; } maxi = - 1 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( vis [ i ] ) dfs2 ( i , 0 ) ; } } static void Main ( ) { for ( int i = 0 ; i < MAX ; i ++ ) adjacent . Add ( new List < int > ( ) ) ; N = 4 ; adjacent [ 1 ] . Add ( 2 ) ; adjacent [ 2 ] . Add ( 1 ) ; adjacent [ 1 ] . Add ( 3 ) ; adjacent [ 3 ] . Add ( 1 ) ; adjacent [ 1 ] . Add ( 4 ) ; adjacent [ 4 ] . Add ( 1 ) ; findNodes ( ) ; Console . WriteLine ( " ( " + startnode + " , ▁ " + endnode + " , ▁ " + thirdnode + " ) " ) ; } }