656. Connecting Cities With Minimum Cost

There are n cities labeled from 1 to n, and edges[i] = [u, v, cost] represents a bidirectional road between city u and city v with a construction cost of cost. Your task is to find the minimum cost to connect all the cities such that every city is reachable from any other city.

Return the minimum cost to connect all the cities. If it is impossible to connect all cities, return -1.

Example 1:

Input: n = 3, edges = [[1,2,5],[1,3,6],[2,3,1]]

Output: 6

Explanation: The minimum spanning tree consists of edges [2,3,1] and [1,2,5], with a total cost of 6.

Example 2:

Input: n = 4, edges = [[1,2,3],[3,4,4]]

Output: -1

Explanation: It is impossible to connect all cities, as city 4 cannot be reached from city 1.

Now Your Turn!

Pick the correct output for the given input

Input: n=5, edges=[[1,2,2], [2,3,3], [3,4,4],[4,5,5],[1,5,10]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 1000
  • 1 <= edges.length <= 200000
  • 1 <= cost <= 10^6
  • The input guarantees that there are no duplicate edges.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int minimumCost(int n, vector<vector<int>>& connections) {
// Your Code Goes Here
}
};
Test Case

Input:

Edges
N