Minimize operations to convert each node of N | C # program for the above approach ; Create adjacency list ; Function to add an edges in graph ; Function to perform the DFS of graph recursively from a given vertex u ; Check for the condition for the flipping of node 's initial value ; Traverse all the children of the current source node u ; Swap foo and foo1 signifies there is change of level ; Function to perform the DFSUtil ( ) for all the unvisited vertices ; Traverse the given set of nodes ; If the current node is unvisited ; Print the number of operations ; Function to count the number of flips required to change initial node values to final node value ; Add the given edges ; DFS Traversal ; Driver code
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static int N = 3 ; static List < List < int > > adj = new List < List < int > > ( ) ; static List < bool > visited ; static int ans ; static void addEdges ( int u , int v ) { adj [ u ] . Add ( v ) ; adj [ v ] . Add ( u ) ; } static void DFSUtil ( int u , bool foo , bool foo1 , bool [ ] initial , bool [ ] finall ) { visited [ u ] = true ; if ( ( initial [ u - 1 ] ^ foo ) ^ finall [ u - 1 ] == true ) { ans += 1 ; foo ^= true ; } for ( int i = 0 ; i < adj [ u ] . Count ; i ++ ) { if ( visited [ adj [ u ] [ i ] ] == false ) DFSUtil ( adj [ u ] [ i ] , foo1 , foo , initial , finall ) ; } } static void DFS ( int V , bool [ ] initial , bool [ ] finall ) { ans = 0 ; visited = new List < bool > ( ) ; for ( int i = 0 ; i < V ; i ++ ) { visited . Add ( false ) ; } for ( int u = 1 ; u <= 1 ; u ++ ) { if ( visited [ u ] == false ) DFSUtil ( u , false , false , initial , finall ) ; } Console . Write ( ans ) ; } static void countOperations ( int N , bool [ ] initial , bool [ ] finall , int [ , ] Edges ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { addEdges ( Edges [ i , 0 ] , Edges [ i , 1 ] ) ; } DFS ( N + 1 , initial , finall ) ; } static void Main ( ) { for ( int i = 0 ; i < N + 1 ; i ++ ) { adj . Add ( new List < int > ( ) ) ; } int [ , ] Edges = { { 1 , 2 } , { 1 , 3 } } ; bool [ ] initial = { true , true , false } ; bool [ ] finall = { false , true , true } ; countOperations ( N , initial , finall , Edges ) ; } }