AlgoFrames

MST on a dense matrix graph

Challenge · Write code · about 20 min

m is an n × n symmetric matrix. m[u][v] is the weight of the edge u-v, or 0 when there is no edge. Return the weight of a minimum spanning tree, or -1 when the graph is not connected.

Aim for O(n²) time and O(n) extra space: do not build an edge list.

Example 1

Input:

[[[0,2,6,9],[2,0,3,8],[6,3,0,5],[9,8,5,0]]]

Output:

10

Edges 0-1 (2), 1-2 (3) and 2-3 (5).

Example 2

Input:

[[[0,4,0],[4,0,0],[0,0,0]]]

Output:

-1

Vertex 2 has no edges.

Constraints

  • 1 ≤ n ≤ 100
  • m[u][v] = m[v][u]
  • 0 ≤ m[u][v] ≤ 1000
  • m[u][u] = 0

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

More Prim's algorithm problems