Minimum steps to color the tree with given colors | C # implementation of the approach ; To store the required answer ; To store the graph ; Function to add edges ; Dfs function ; When there is difference in colors ; For all it 's child nodes ; Driver code ; Here zero is for parent of node 1 ; Adding edges in the graph ; Dfs call ; Required answer
using System ; using System . Collections . Generic ; class GFG { static int ans = 0 ; static List < List < int > > gr = new List < List < int > > ( ) ; static void Add_Edge ( int u , int v ) { gr [ u ] . Add ( v ) ; gr [ v ] . Add ( u ) ; } static void dfs ( int child , int par , int [ ] color ) { if ( color [ child ] != color [ par ] ) ans ++ ; for ( int i = 0 ; i < gr [ child ] . Count ; i ++ ) { if ( gr [ child ] [ i ] == par ) continue ; dfs ( gr [ child ] [ i ] , child , color ) ; } } public static void Main ( String [ ] args ) { for ( int i = 0 ; i <= 10 ; i ++ ) gr . Add ( new List < int > ( ) ) ; int [ ] color = { 0 , 1 , 2 , 3 , 2 , 2 , 3 } ; Add_Edge ( 1 , 2 ) ; Add_Edge ( 1 , 3 ) ; Add_Edge ( 2 , 4 ) ; Add_Edge ( 2 , 5 ) ; Add_Edge ( 3 , 6 ) ; dfs ( 1 , 0 , color ) ; Console . WriteLine ( ans ) ; } }