> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Min Cost to Connect All Points Python Solution

> Tested Python solution for LeetCode 1584 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 1584, Medium. Topics: Array, Union-Find, Graph Theory, Minimum Spanning Tree. [View on LeetCode](https://leetcode.com/problems/min-cost-to-connect-all-points/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1584   # by problem number
lcpy gen -s min_cost_to_connect_all_points   # by problem name
```

## Problem

You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.

The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.

Return *the minimum cost to make all points connected*. All points are connected if there is **exactly one** simple path between any two points.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2020/08/26/d.png)

```
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:
![Example 1 solution](https://assets.leetcode.com/uploads/2020/08/26/c.png)
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
```

```
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
```

### Constraints

* 1 \<= points.length \<= 1000
* -10^6 \<= xi, yi \<= 10^6
* All pairs (xi, yi) are distinct.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/min_cost_to_connect_all_points/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/min_cost_to_connect_all_points/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heapq


class Solution:
    # Time: O(n^2 * log(n)) for Prim's algorithm
    # Space: O(n)
    def min_cost_connect_points(self, points: list[list[int]]) -> int:
        n = len(points)
        if n <= 1:
            return 0

        def manhattan_distance(p1: list[int], p2: list[int]) -> int:
            return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])

        visited = [False] * n
        min_heap: list[tuple[int, int]] = [(0, 0)]  # (cost, node)
        total_cost = 0
        edges_used = 0

        while min_heap and edges_used < n:
            cost, node = heapq.heappop(min_heap)
            if visited[node]:
                continue
            visited[node] = True
            total_cost += cost
            edges_used += 1

            for neighbor in range(n):
                if not visited[neighbor]:
                    distance = manhattan_distance(points[node], points[neighbor])
                    heapq.heappush(min_heap, (distance, neighbor))

        return total_cost
```

## Complexity

| Time                                  | Space |
| ------------------------------------- | ----- |
| O(n^2 \* log(n)) for Prim's algorithm | O(n)  |

## Tags

[NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
