Find minimum weight valid edge .
int min = INT_MAX , a = - 1 , b = - 1 ; for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { if ( cost [ i ] [ j ] < min ) { if ( isValidEdge ( i , j , inMST ) ) { min = cost [ i ] [ j ] ; a = i ; b = j ; } } } } if ( a != - 1 && b != - 1 ) { System . out . printf ( "Edge %d:(%d, %d) cost: %d NEW_LINE", edge_count++, a, b, min); mincost = mincost + min ; inMST [ b ] = inMST [ a ] = true ; } } System . out . printf ( " Minimum cost = % d ", mincost); }