[Swift]LeetCode1135. 最低成本聯通全部城市 | Connecting Cities With Minimum Cost

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-zxgnceqp-ku.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

There are N cities numbered from 1 to N.git

You are given connections, where each connections[i] = [city1, city2, cost] represents the cost to connect city1 and city2 together.  (A connection is bidirectional: connecting city1 and city2is the same as connecting city2 and city1.)github

Return the minimum cost so that for every pair of cities, there exists a path of connections (possibly of length 1) that connects those two cities together.  The cost is the sum of the connection costs used. If the task is impossible, return -1.微信

 

Example 1:code

Input: N = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Output: 6
Explanation: 
Choosing any 2 edges will connect all cities so we choose the minimum 2.

Example 2:htm

Input: N = 4, connections = [[1,2,3],[3,4,4]]
Output: -1
Explanation: 
There is no way to connect all cities even if all edges are used.

Note:blog

  1. 1 <= N <= 10000
  2. 1 <= connections.length <= 10000
  3. 1 <= connections[i][0], connections[i][1] <= N
  4. 0 <= connections[i][2] <= 10^5
  5. connections[i][0] != connections[i][1]

想象一下你是個城市基建規劃者,地圖上有 N 座城市,它們按以 1 到 N 的次序編號。ci

給你一些可鏈接的選項 conections,其中每一個選項 conections[i] = [city1, city2, cost] 表示將城市 city1 和城市 city2 鏈接所要的成本。(鏈接是雙向的,也就是說城市 city1 和城市 city2 相連也一樣意味着城市 city2 和城市 city1 相連)。leetcode

返回使得每對城市間都存在將它們鏈接在一塊兒的連通路徑(可能長度爲 1 的)最小成本。該最小成本應該是所用所有鏈接代價的綜合。若是根據已知條件沒法完成該項任務,則請你返回 -1。get

示例 1:

輸入:N = 3, conections = [[1,2,5],[1,3,6],[2,3,1]]
輸出:6
解釋:
選出任意 2 條邊均可以鏈接全部城市,咱們從中選取成本最小的 2 條。

示例 2:

輸入:N = 4, conections = [[1,2,3],[3,4,4]]
輸出:-1
解釋: 
即便連通全部的邊,也沒法鏈接全部城市。

提示:

  1. 1 <= N <= 10000
  2. 1 <= conections.length <= 10000
  3. 1 <= conections[i][0], conections[i][1] <= N
  4. 0 <= conections[i][2] <= 10^5
  5. conections[i][0] != conections[i][1]
相關文章
相關標籤/搜索