There are n cities labeled from 1 to n. You are given the integer n
and an array connections where connections[i] = [xi, yi, costi] indicates that the cost of connecting city xi and city yi (bidirectional connection) is costi.
Return _the minimumcost to connect all the _ncities such that there is at least one path between each pair of cities. If it is impossible to connect all the n cities, return -1,
The cost is the sum of the connections’ costs used.
To connect all cities with minimum cost, we need to find a Minimum Spanning Tree (MST) of the graph formed by the cities and connections. Kruskal’s algorithm is efficient for this, as it sorts all edges by cost and greedily adds the smallest edge that doesn’t form a cycle, using Union-Find to track connected components.
classSolution {
publicintminimumCost(int n, int[][] connections) {
Arrays.sort(connections, Comparator.comparingInt(a -> a[2]));
int[] p =newint[n+1];
for (int i = 0; i <= n; i++) p[i]= i;
int ans = 0, cnt = 0;
for (int[] e : connections) {
int u = find(p, e[0]), v = find(p, e[1]);
if (u != v) {
p[u]= v;
ans += e[2];
cnt++;
}
}
return cnt == n-1 ? ans : -1;
}
intfind(int[] p, int x) { return p[x]== x ? x : (p[x]= find(p, p[x])); }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funminimumCost(n: Int, connections: Array<IntArray>): Int {
connections.sortBy { it[2] }
val p = IntArray(n+1) { it }
funfind(x: Int): Int = if (p[x] == x) x else { p[x] = find(p[x]); p[x] }
var ans = 0; var cnt = 0for (e in connections) {
val u = find(e[0]); val v = find(e[1])
if (u != v) {
p[u] = v
ans += e[2]
cnt++ }
}
returnif (cnt == n-1) ans else -1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defminimumCost(self, n: int, connections: list[list[int]]) -> int:
p = list(range(n+1))
deffind(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
ans = cnt =0for x, y, c in sorted(connections, key=lambda x: x[2]):
u, v = find(x), find(y)
if u != v:
p[u] = v
ans += c
cnt +=1return ans if cnt == n-1else-1
⏰ Time complexity: O(m log m + m α(n)), where m is the number of connections and n is the number of cities. Sorting takes O(m log m), and each union/find is nearly constant time.
🧺 Space complexity: O(n), for the Union-Find parent array.