Advanced Graphs Minimum spanning trees
486. Minimum Spanning Tree Weight
You are given a connected undirected graph with n vertices, numbered from 0 to n - 1. Each row
edges[i] = [u, v, w] is an edge of weight w between vertices u and v. Two edges can join the same two
vertices, and an edge can join a vertex to itself.
A spanning tree is a set of n - 1 edges of the graph that connects all the vertices, so every vertex can
reach every other one along these edges. Its weight is the sum of the weights of its edges. Return the
smallest weight a spanning tree of the graph can have.
Example 1
Input: n = 5
edges = [[0, 1, 4],
[0, 2, 3],
[1, 2, 1],
[1, 3, 2],
[2, 3, 4],
[3, 4, 2],
[2, 4, 6]]
8Explanation: The cheapest spanning tree takes [1, 2, 1], [1, 3, 2], [3, 4, 2] and [0, 2, 3]. Its weight is
1 + 2 + 2 + 3 = 8.
Example 2
Input: n = 3
edges = [[0, 1, 6],
[1, 1, 0],
[1, 0, 2],
[2, 2, 1],
[1, 2, 3]]
5Explanation: Of the two edges between vertices 0 and 1, the tree takes the one of weight 2. It adds [1, 2, 3], so the
weight is 5. The edges [1, 1, 0] and [2, 2, 1] join a vertex to itself and connect nothing.
Example 3
Input: n = 4
edges = [[0, 1, 1000000000],
[1, 2, 1000000000],
[2, 3, 1000000000],
[3, 0, 1000000000]]
3000000000Explanation: The four edges form a loop, and any three of them connect the vertices. Each weighs 109, so the weight is 3 × 109.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 105edges[i] = [u, v, w], with0 ≤ u, v < nand0 ≤ w ≤ 109- The graph is connected.
- Two edges can join the same two vertices, and an edge can join a vertex to itself.
Clarifying questions
What you would ask an interviewer before writing any code.