150強訪談簡單

連接所有點的最小成本

「連接所有點的最小成本」問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個陣列點,表示 2D 平面上某些點的整數座標,其中點[i] = [xi, yi]。

連接兩點 [xi, yi] 和 [xj, yj] 的成本是它們之間的曼哈頓距離: |xi - xj| + |yi - yj|,其中 |val|是 val 的絕對值。

傳回連接所有點的最小成本。如果任兩點之間恰好存在一條簡單路徑,則所有點都是相連的。

寫一個函數 minCostConnectPoints(points: List[List[int]]) -> int

約束條件
  • 1 <= len(points) <= 1000
  • -10^6 <= xi, yi <= 10^6
  • All points are distinct

範例

Example 1
Input
points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output
20
Explanation

Connect points as: (0,0)-(2,2) cost 4, (2,2)-(5,2) cost 3, (5,2)-(7,0) cost 4, (2,2)-(3,10) cost 9. Total = 20.

Example 2
Input
points = [[3,12],[-2,5],[-4,1]]
Output
18
Explanation

Connecting points: (-4,1) to (-2,5) with cost 6, (-2,5) to (3,12) with cost 12. Total 18.

Need a Hint?
考慮使用高階圖特定的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。