Skip to content

Commit 338346e

Browse files
committed
1584-min-cost-to-connect-all-points-2.md Added Kruskal's Algorithm and heap sort for Prim algorithm.
1 parent 2645fba commit 338346e

4 files changed

+214
-4
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,6 @@ You can skip the more difficult problems and do them later.
7373
- [1971. Find if Path Exists in Graph](solutions/1001-2000/1971-find-if-path-exists-in-graph.md) was solved in _Python, Java, C++, JavaScript, C#, Go, Ruby_ and 2 solutions.
7474
- [684. Redundant Connection](solutions/1-1000/684-redundant-connection.md) was solved in _Python, Java, C++, JavaScript, C#, Go, Ruby_.
7575
- [685. Redundant Connection II](solutions/1-1000/685-redundant-connection-ii.md) was solved in _Python_.
76-
- [1584. Min Cost to Connect All Points](solutions/1001-2000/1584-min-cost-to-connect-all-points.md) was solved in _Python, Java, C++, JavaScript, C#, Go, Ruby_.
76+
- [1584. Min Cost to Connect All Points](solutions/1001-2000/1584-min-cost-to-connect-all-points.md) was solved in _Python, Java, C++, JavaScript, C#, Go, Ruby_ and 2 solutions.
7777

7878
More LeetCode problems will be added soon...
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
# 1584. Min Cost to Connect All Points LeetCode Solution (Kruskal's Algorithm)
2+
LeetCode problem link: [1584. Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points)
3+
4+
## LeetCode problem description
5+
You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
6+
7+
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`.
8+
9+
Return _the minimum cost to make all points connected_. All points are connected if there is **exactly one** simple path between any two points.
10+
11+
### Example 1
12+
![](../../images/examples/1584_1_1.png)
13+
```java
14+
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
15+
Output: 20
16+
Explanation:
17+
```
18+
![](../../images/examples/1584_1_2.png)
19+
```
20+
We can connect the points as shown above to get the minimum cost of 20.
21+
Notice that there is a unique path between every pair of points.
22+
```
23+
24+
### Example 2
25+
```java
26+
Input: points = [[3,12],[-2,5],[-4,1]]
27+
Output: 18
28+
```
29+
30+
### Constraints
31+
- `1 <= points.length <= 1000`
32+
- `-1000000 <= xi, yi <= 1000000`
33+
- All pairs `(xi, yi)` are distinct.
34+
35+
<details>
36+
<summary>Hint 1</summary>
37+
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points.
38+
</details>
39+
40+
<details>
41+
<summary>Hint 2</summary>
42+
The problem is now the cost of minimum spanning tree in graph with above edges.
43+
</details>
44+
45+
## Intuition
46+
* Connect each pair of points with a **weighted** edge, the weight being the manhattan distance between those points.
47+
* Cycles will increase the `cost`, so there is no cycle.
48+
* A connected graph without cycles is called a tree.
49+
* The problem is now the cost of **minimum spanning tree** in graph with above edges.
50+
* A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight.
51+
52+
### Another solution: Prim's Algorithm
53+
Please see [1584. Min Cost to Connect All Points (Prim's Algorithm)](1584-min-cost-to-connect-all-points.md).
54+
55+
This page, I will only talk about the solution of **Kruskal's Algorithm**.
56+
57+
### Approach: Kruskal's Algorithm
58+
- _Prim's Algorithm_ adds the closest point to the tree each time, while _Kruskal's Algorithm_ adds the shortest edge to the tree each time.
59+
- If both vertices of an edge are already in the tree, this edge can be skipped. Because once this edge is added, a cycle will be formed, which will increase the cost and destroy the structure of the tree.
60+
- To determine whether a cycle will be formed, the **Union-Find** algorithm can be used.
61+
- Traverse all edges once, add up the lengths of the edges and return the sum as the result.
62+
- If you are familiar with the **Union-Find** algorithm, it is easy to solve the problem with _Kruskal's algorithm_. However, this problem does not directly give the `edges` information, and we need to calculate it through the vertex information, which is not difficult, but this causes the algorithm to run slower than _Prim's Algorithm_ because there are too many edges. The more edges, the slower _Kruskal's Algorithm_.
63+
64+
## Complexity
65+
`E` is the `edges.length`.
66+
67+
`N` is the `points.length`.
68+
69+
* Time: `O(E * logE)`.
70+
* Space: `O(N * N)`.
71+
72+
## Python
73+
```python
74+
class Solution:
75+
def __init__(self):
76+
self.parent = []
77+
78+
def minCostConnectPoints(self, points: List[List[int]]) -> int:
79+
self.parent = list(range(len(points)))
80+
result = 0
81+
edged_points = []
82+
83+
for i, point in enumerate(points):
84+
for j in range(i + 1, len(points)):
85+
distance = abs(point[0] - points[j][0]) + \
86+
abs(point[1] - points[j][1])
87+
heapq.heappush(edged_points, (distance, i, j))
88+
89+
while edged_points:
90+
distance, i, j = heapq.heappop(edged_points)
91+
92+
if self.same_root(i, j):
93+
continue
94+
95+
self.unite(i, j)
96+
97+
result += distance
98+
99+
return result
100+
101+
def unite(self, x, y):
102+
root_x = self.find_root(x)
103+
root_y = self.find_root(y)
104+
self.parent[root_y] = root_x
105+
106+
def find_root(self, x):
107+
if x == self.parent[x]:
108+
return x
109+
110+
self.parent[x] = self.find_root(self.parent[x])
111+
112+
return self.parent[x]
113+
114+
def same_root(self, x, y):
115+
return self.find_root(x) == self.find_root(y)
116+
```
117+
118+
## Java
119+
```java
120+
```
121+
122+
## Python
123+
```python
124+
// Welcome to create a PR to complete the code of this language, thanks!
125+
```
126+
127+
## C++
128+
```cpp
129+
// Welcome to create a PR to complete the code of this language, thanks!
130+
```
131+
132+
## JavaScript
133+
```javascript
134+
// Welcome to create a PR to complete the code of this language, thanks!
135+
```
136+
137+
## C#
138+
```c#
139+
// Welcome to create a PR to complete the code of this language, thanks!
140+
```
141+
142+
## Go
143+
```go
144+
// Welcome to create a PR to complete the code of this language, thanks!
145+
```
146+
147+
## C
148+
```c
149+
// Welcome to create a PR to complete the code of this language, thanks!
150+
```
151+
152+
## Kotlin
153+
```kotlin
154+
// Welcome to create a PR to complete the code of this language, thanks!
155+
```
156+
157+
## Swift
158+
```swift
159+
// Welcome to create a PR to complete the code of this language, thanks!
160+
```
161+
162+
## Rust
163+
```rust
164+
// Welcome to create a PR to complete the code of this language, thanks!
165+
```
166+
167+
## Other languages
168+
```
169+
// Welcome to create a PR to complete the code of this language, thanks!
170+
```

solutions/1001-2000/1584-min-cost-to-connect-all-points.md

+42-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# LeetCode 1584. Min Cost to Connect All Points' Solution
1+
# 1584. Min Cost to Connect All Points' LeetCode Solution (Prim's Algorithm)
22
LeetCode problem link: [1584. Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points)
33

44
## LeetCode problem description
@@ -50,7 +50,12 @@ Output: 18
5050
* A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight.
5151
* One of the solutions for `MST` is the **Prim algorithm**, which is a _greedy algorithm_ and also a _dynamic programming algorithm_.
5252

53-
### Prim algorithm
53+
### Another solution: Kruskal's Algorithm
54+
Please see [1584. Min Cost to Connect All Points (Kruskal's Algorithm)](1584-min-cost-to-connect-all-points-2.md).
55+
56+
This page, I will only talk about the solution of **Prim's Algorithm**.
57+
58+
### Prim's Algorithm
5459
- Initially, add any point to an empty graph, for example, the point with index 0.
5560
- Next, add the second point. This second point is the **closest** point to the first point.
5661
- An `min_distances` (or call it `dp`) array is needed to store the distances of other points to the first point.
@@ -172,10 +177,12 @@ for i, point in enumerate(points):
172177
* Return `sum(min_distances)`.
173178

174179
## Complexity
180+
`n` is the `points.length`.
175181
* Time: `O(n * n)`.
176182
* Space: `O(n)`.
177183

178184
## Python
185+
### Solution 1: Not use 'heap sort'
179186
```python
180187
class Solution:
181188
def minCostConnectPoints(self, points: List[List[int]]) -> int:
@@ -209,6 +216,39 @@ class Solution:
209216
return sum(min_distances)
210217
```
211218

219+
### Solution 2: Use 'heap sort'
220+
* If you use `heap sort`, `current_index`, `next_index` is not needed, because heap sort knows which is the minimum value.
221+
* `visited` is also not needed, because each `heappop()` means that a point has been `visited`.
222+
223+
```python
224+
class Solution:
225+
def minCostConnectPoints(self, points: List[List[int]]) -> int:
226+
result = 0
227+
min_distances = []
228+
229+
for i in range(len(points)):
230+
min_distances.append([float('inf'), i])
231+
232+
min_distances[0][0] = 0
233+
234+
while min_distances:
235+
distance, index = heapq.heappop(min_distances)
236+
result += distance
237+
238+
for min_distance in min_distances:
239+
point = points[min_distance[1]]
240+
241+
min_distance[0] = min(
242+
min_distance[0],
243+
abs(point[0] - points[index][0]) + \
244+
abs(point[1] - points[index][1])
245+
)
246+
247+
heapq.heapify(min_distances)
248+
249+
return result
250+
```
251+
212252
## Java
213253
```java
214254
class Solution {

solutions/1001-2000/1971-find-if-path-exists-in-graph-2.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ This graph may have multiple **connected components**.
6666
* Space: `O(n)`.
6767

6868
## Python
69-
### Standard UnionFind algorithm
69+
### Standard UnionFind algorithm (recommended)
7070
```python
7171
class Solution:
7272
def __init__(self):

0 commit comments

Comments
 (0)