Minimize operations to convert each node of N | 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
let N = 3 ; let adj = [ ] ; for ( let i = 0 ; i < N + 1 ; i ++ ) { adj . push ( [ ] ) ; } let visited ; let ans ; function addEdges ( u , v ) { adj [ u ] . push ( v ) ; adj [ v ] . push ( u ) ; } function DFSUtil ( u , foo , foo1 , initial , finall ) { visited [ u ] = true ; if ( ( initial [ u - 1 ] ^ foo ) ^ finall [ u - 1 ] == true ) { ans += 1 ; foo ^= true ; } for ( let i = 0 ; i < adj [ u ] . length ; i ++ ) { if ( visited [ adj [ u ] [ i ] ] == false ) DFSUtil ( adj [ u ] [ i ] , foo1 , foo , initial , finall ) ; } } function DFS ( V , initial , finall ) { ans = 0 ; visited = new Array ( V ) ; visited . fill ( false ) ; for ( let u = 1 ; u <= 1 ; u ++ ) { if ( visited [ u ] == false ) DFSUtil ( u , 0 , 0 , initial , finall ) ; } document . write ( ans ) ; } function countOperations ( N , initial , finall , Edges ) { for ( let i = 0 ; i < N - 1 ; i ++ ) { addEdges ( Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) ; } DFS ( N + 1 , initial , finall ) ; } let Edges = [ [ 1 , 2 ] , [ 1 , 3 ] ] ; let initial = [ true , true , false ] ; let finall = [ false , true , true ] ; countOperations ( N , initial , finall , Edges ) ;