Skip to contentKEEP THE CRAFTTHE SANCTUARY

Grow a Spanning Tree with Prim

Grow a minimum spanning tree from node 0 with Prim's algorithm: a min-heap of edges leaving the tree.

The problem

Implement prim_spanning_weight(node_count, edges). The nodes are labeled 0 to node_count - 1, with node_count >= 1, and each edge [u, v, weight] connects u and v in both directions. Return the total weight of a minimum spanning tree, the cheapest set of edges that connects every node, or -1 if the graph is not connected. Weights can be negative, and two nodes may be joined by more than one edge. Grow the tree from node 0 with Prim's algorithm. For example, with 4 nodes and edges [[0, 1, 4], [0, 2, 1], [2, 1, 2], [1, 3, 1], [2, 3, 5]] the answer is 4, using the edges 0-2, 2-1 and 1-3.

Starter code

def prim_spanning_weight(node_count, edges):
    pass

Public examples

  1. node_count = 4, edges = [[0, 1, 4], [0, 2, 1], [2, 1, 2], [1, 3, 1], [2, 3, 5]]gives4
  2. node_count = 3, edges = [[0, 1, 1]]gives-1

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.