Skip to content
DeepForgeby svx
All problems
MediumGraph Algorithmsgraph-024

Prim MST Weight

Problem

Compute the total weight of a minimum spanning tree of a connected undirected weighted graph using Prim's algorithm.

edges is a list of [u, v, w] triples. Return -1 when the graph is disconnected and 0 when there is a single node.

Hint

Grow the tree one cheapest crossing edge at a time.

Test cases

case 1
in: [4,[[0,1,1],[0,2,3],[1,2,1],[1,3,4],[2,3,2]]]
expected: 4
case 2
in: [3,[[0,1,1]]]
expected: -1
case 3
in: [1,[]]
expected: 0
case 4
in: [2,[[0,1,7]]]
expected: 7
Starter codePython
import heapq
def prim_mst_weight(n, edges):
    # Your code here
    pass

4 test cases · run your code against them in the editor