Connecting Cities With Minimum Cost
There are n cities labeled 1..n. You are given connections where each entry [city1, city2, cost] is a bidirectional link that can be built for the given cost. Return the minimum total cost to connect all cities so that every pair is reachable, or -1 if it is impossible to connect them all.
Open official problem prompt ↗Find the cheapest set of links that makes all n cities mutually reachable.
A road department with a fixed map of possible roads and their prices wants every town linked; it builds the cheapest roads first, skipping any that would connect two towns already joined by another route.
- Input
- n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
- Output
- 6
- Why
- Choosing edges 2-3 (cost 1) and 1-2 (cost 5) connects all three cities for 6, the cheapest spanning tree.
1 <= n <= 10^41 <= connections.length <= 10^4connections[i].length == 31 <= city1, city2 <= ncity1 != city20 <= cost <= 10^5