AlgoFrames

Implement Prim

Standard · Write code · about 15 min

Grow a minimum spanning tree from vertex 0 and return its total weight. Return -1 when some vertex cannot be reached.

buildAdjacency(graph) lists [neighbor, weight] pairs in JavaScript. In Python, build the lists from graph["edges"].

Example 1

Input:

[{"n":6,"edges":[[0,1,3],[0,2,1],[1,2,2],[1,3,6],[2,4,5],[3,4,4],[3,5,7],[4,5,8]],"directed":false}]

Output:

19

Vertices join in the order 0, 2, 1, 4, 3, 5.

Example 2

Input:

[{"n":5,"edges":[[0,1,2],[1,2,3],[3,4,1]],"directed":false}]

Output:

-1

Vertices 3 and 4 are never reached from 0.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ edges.length ≤ 500
  • 0 ≤ w ≤ 100
  • No self-loops.

Learn the idea first: Prim's algorithm, a visual lesson.

More Prim's algorithm problems