We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
/*
* Complete the 'prims' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. 2D_INTEGER_ARRAY edges
* 3. INTEGER start
*/
function prims(edges, mst = [total = 0;
// Sort edges based on weight
usort(`$edges, function($`a, $b) {
return `$a[2] - $`b[2];
});
// Prim's algorithm: Add the lowest weight edge that connects to the MST
while (count(`$mst) < $`n) {
foreach (`$edges as $`edge) {
list(`$u, $`v, `$w) = $`edge;
`$uInMST = in_array($`u, $mst);
`$vInMST = in_array($`v, $mst);
// Check if one vertex is in MST and the other is not (XOR logic)
if (`$uInMST xor $`vInMST) {
// Add vertices to MST
if (!`$uInMST) $`mst[] = $u;
if (!`$vInMST) $`mst[] = $v;
// Add weight to total
`$total += $`w;
break;
}
}
}
return $total;
}
fwrite(result . "\n");
fclose($fptr);
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Prim's (MST) : Special Subtree
You are viewing a single comment's thread. Return to all comments →
/* * Complete the 'prims' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER n * 2. 2D_INTEGER_ARRAY edges * 3. INTEGER start */
function prims(edges, mst = [total = 0;
}
fwrite(result . "\n");
fclose($fptr);