Minimize cost to color all the vertices of an Undirected Graph using given operation | JavaScript Program to find the minimum cost to color all vertices of an Undirected Graph ; Function to add edge in the given graph ; Function to perform DFS traversal and find the node with minimum cost ; Update the minimum cost ; Recur for all connected nodes ; Function to calculate and return the minimum cost of coloring all vertices of the Undirected Graph ; Marks if a vertex is visited or not ; Perform DFS traversal ; If vertex is not visited ; Update minimum cost ; Return the final cost ; Driver Code
var MAX = 10 var adj = Array . from ( Array ( MAX ) , ( ) => Array ( ) ) ; function addEdge ( u , v ) { adj [ u ] . push ( v ) ; adj [ v ] . push ( u ) ; } function dfs ( v , cost , vis , min_cost_node ) { vis [ v ] = true ; min_cost_node = Math . min ( min_cost_node , cost [ v - 1 ] ) ; for ( var i = 0 ; i < adj [ v ] . length ; i ++ ) { if ( vis [ adj [ v ] [ i ] ] == false ) { min_cost_node = dfs ( adj [ v ] [ i ] , cost , vis , min_cost_node ) ; } } return min_cost_node ; } function minimumCost ( V , cost ) { var vis = Array ( V + 1 ) . fill ( false ) ; var min_cost = 0 ; for ( var i = 1 ; i <= V ; i ++ ) { if ( ! vis [ i ] ) { var min_cost_node = 1000000000 ; min_cost_node = dfs ( i , cost , vis , min_cost_node ) ; min_cost += min_cost_node ; } } return min_cost ; } var V = 6 , E = 5 ; var cost = [ 12 , 25 , 8 , 11 , 10 , 7 ] ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 3 , 2 ) ; addEdge ( 2 , 5 ) ; addEdge ( 4 , 6 ) ; var min_cost = minimumCost ( V , cost ) ; document . write ( min_cost ) ;