AlgoFrames

Implement Kruskal

Standard · Write code · about 15 min

Return the total weight of a minimum spanning tree of the undirected graph graph. Return -1 when the graph is not connected.

graph.n is the number of vertices and graph.edges lists [u, v, w] triples.

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

The MST uses 0-2, 1-2, 3-4, 2-4 and 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 cannot reach the others.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ edges.length ≤ 500
  • 0 ≤ w ≤ 100
  • No self-loops and no repeated pairs.

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

More Kruskal's algorithm problems