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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。