All problems
Prim Minimum Spanning Tree
Problem
Given n nodes and undirected weighted edges as [u, v, w] triples, return the total weight of a minimum spanning tree, or -1 if the graph is disconnected.
Grow the tree from node 0 using a min-heap of candidate edges, skipping nodes already in the tree. A single node has weight 0.
Hint
The starting node is free; every later pop adds one new node and its cheapest connecting edge.
Test cases
case 1
in: [4,[[0,1,1],[0,2,4],[1,2,2],[1,3,5],[2,3,3]]]
expected: 6
case 2
in: [1,[]]
expected: 0
case 3
in: [3,[[0,1,1]]]
expected: -1
case 4
in: [5,[[0,1,2],[0,2,3],[1,2,1],[2,3,4],[3,4,5],[2,4,6]]]
expected: 12
case 5
in: [2,[[0,1,7]]]
expected: 7
Starter codePython
def prim_mst(n, edges):
# Your code here
pass5 test cases · run your code against them in the editor