Skip to content

Commit ddbe511

Browse files
committed
Added the Solution of Min Cost to Connect All Points
1 parent 38192bb commit ddbe511

File tree

2 files changed

+379
-1
lines changed

2 files changed

+379
-1
lines changed

dsa-problems/leetcode-problems/1500-1599.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,7 @@ export const problems = [
518518
"problemName": "1584. Min Cost to Connect All Points",
519519
"difficulty": "Medium",
520520
"leetCodeLink": "https://leetcode.com/problems/min-cost-to-connect-all-points",
521-
"solutionLink": "#"
521+
"solutionLink": "/dsa-solutions/lc-solutions/1500-1599/min-cost-to-connect-all-points"
522522
},
523523
{
524524
"problemName": "1585. Check If String Is Transformable With Substring Sort Operations",
Lines changed: 378 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,378 @@
1+
---
2+
id: min-cost-to-connect-all-points
3+
title: Min Cost to Connect All Points
4+
sidebar_label: 1584.Min Cost to Connect All Points
5+
6+
tags:
7+
- Array
8+
- Union Find
9+
- Graph
10+
- Minimum Spanning Tree
11+
12+
description: "This is a solution to the Min Cost to Connect All Points problem on LeetCode."
13+
---
14+
15+
## Problem Description
16+
You are given an array points representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi].`
17+
18+
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.
19+
20+
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
21+
22+
### Examples
23+
**Example 1:**
24+
![image](https://assets.leetcode.com/uploads/2020/08/26/d.png)
25+
```
26+
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
27+
Output: 20
28+
Explanation:
29+
![image](https://assets.leetcode.com/uploads/2020/08/26/c.png)
30+
We can connect the points as shown above to get the minimum cost of 20.
31+
Notice that there is a unique path between every pair of points.
32+
33+
```
34+
35+
### Constraints
36+
- `1 <= points.length <= 1000`
37+
- `-10^6 <= xi, yi <= 10^6`
38+
- `All pairs (xi, yi) are distinct.`
39+
40+
## Solution for Min Cost to Connect All Points
41+
### Approach
42+
#### Prim's algorithm:
43+
44+
- Prim's algorithm is an algorithm for solving the optimization problem of finding the minimum spanning tree in a weighted connected graph within graph theory. A minimum spanning tree is a subset of the edges of the graph that forms a tree containing all vertices while minimizing the total weight of those edges.
45+
46+
#### Overview of the Algorithm:
47+
48+
- Calculate the distances between each pair of points and use Prim's algorithm to form the minimum spanning tree.
49+
- Start from an initial point, mark it as visited, and select the point with the smallest distance among the unvisited points.
50+
- Calculate the distances from the selected point to the unvisited points and store them in a cache.
51+
- Add the minimum cost edge to the priority queue using the distances from the cache.
52+
- Repeat the above steps until all points are visited, and calculate the minimum cost.
53+
#### Specific Steps:
54+
55+
#### Initial State:
56+
57+
- n: Number of points
58+
- min_cost: Minimum cost (initially 0) and return value
59+
- visited: A list to indicate if each point is visited (initially all False)
60+
- pq: Priority queue (initially (0, 0) indicating starting from point 0 with cost 0)
61+
- cache: Dictionary for caching distances (initially empty)
62+
#### Each Step:
63+
64+
- Pop cost and point from pq (start from the initial point).
65+
- If the point is already visited, skip this point.
66+
- Otherwise, mark this point as visited and add the current cost to the minimum cost.
67+
- Calculate distances from this point to all unvisited points and store them in the cache. Update the cache if the new distance is smaller.
68+
- Add the point with the smallest distance among the unvisited points to the priority queue using distances from the cache.
69+
- Repeat steps 3 to 5 until all points are visited.
70+
- Return the final minimum cost.
71+
72+
73+
<Tabs>
74+
<TabItem value="Solution" label="Solution">
75+
76+
#### Implementation
77+
```jsx live
78+
function Solution(arr) {
79+
var minCostConnectPoints = function(points) {
80+
let cost = 0;
81+
const n = points.length;
82+
const dist = Array(n).fill(Infinity);
83+
dist[0] = 0;
84+
let next = 0;
85+
86+
for (let step = 1; step < n; step++) {
87+
let min = Infinity;
88+
let point = -1;
89+
for (let i = 1; i < n; i++) {
90+
if (dist[i] > 0) {
91+
dist[i] = Math.min(dist[i], Math.abs(points[i][0] - points[next][0]) + Math.abs(points[i][1] - points[next][1]));
92+
if (dist[i] < min) {
93+
min = dist[i];
94+
point = i;
95+
}
96+
}
97+
}
98+
cost += min;
99+
dist[point] = 0;
100+
next = point;
101+
}
102+
103+
return cost;
104+
};
105+
const input = [[0,0],[2,2],[3,10],[5,2],[7,0]]
106+
const output =minCostConnectPoints(input)
107+
return (
108+
<div>
109+
<p>
110+
<b>Input: </b>
111+
{JSON.stringify(input)}
112+
</p>
113+
<p>
114+
<b>Output:</b> {output.toString()}
115+
</p>
116+
</div>
117+
);
118+
}
119+
```
120+
121+
#### Complexity Analysis
122+
123+
- Time Complexity: $O(n^2 * log(n)) $
124+
- Space Complexity: $ O(n)$
125+
126+
## Code in Different Languages
127+
<Tabs>
128+
<TabItem value="JavaScript" label="JavaScript">
129+
<SolutionAuthor name="@hiteshgahanolia"/>
130+
```javascript
131+
manhattDist(v1, v2) {
132+
return Math.abs(v1[0] - v2[0]) + Math.abs(v1[1] - v2[1]);
133+
}
134+
135+
minCostConnectPoints(points) {
136+
const n = points.length;
137+
const adj = Array.from({ length: n }, () => []);
138+
139+
for (let i = 0; i < n; i++) {
140+
for (let j = i + 1; j < n; j++) {
141+
const dist = this.manhattDist(points[i], points[j]);
142+
adj[i].push([j, dist]);
143+
adj[j].push([i, dist]);
144+
}
145+
}
146+
147+
const pq = new MinPriorityQueue({ priority: x => x[0] });
148+
const vis = Array(n).fill(false);
149+
pq.enqueue([0, 0]);
150+
let cost = 0;
151+
152+
while (!pq.isEmpty()) {
153+
const [topEdgwWt, currNode] = pq.dequeue().element;
154+
155+
if (vis[currNode]) continue;
156+
vis[currNode] = true;
157+
cost += topEdgwWt;
158+
159+
for (const [adjPoint, edWt] of adj[currNode]) {
160+
if (!vis[adjPoint]) {
161+
pq.enqueue([edWt, adjPoint]);
162+
}
163+
}
164+
}
165+
166+
return cost;
167+
}
168+
```
169+
170+
</TabItem>
171+
<TabItem value="TypeScript" label="TypeScript">
172+
<SolutionAuthor name="@hiteshgahanolia"/>
173+
```typescript
174+
class Solution {
175+
manhattDist(v1: number[], v2: number[]): number {
176+
return Math.abs(v1[0] - v2[0]) + Math.abs(v1[1] - v2[1]);
177+
}
178+
179+
minCostConnectPoints(points: number[][]): number {
180+
const n = points.length;
181+
const adj: [number, number][][] = Array.from({ length: n }, () => []);
182+
183+
for (let i = 0; i < n; i++) {
184+
for (let j = i + 1; j < n; j++) {
185+
const dist = this.manhattDist(points[i], points[j]);
186+
adj[i].push([j, dist]);
187+
adj[j].push([i, dist]);
188+
}
189+
}
190+
191+
const pq = new MinPriorityQueue({ priority: (x: [number, number]) => x[0] });
192+
const vis = Array(n).fill(false);
193+
pq.enqueue([0, 0]);
194+
let cost = 0;
195+
196+
while (!pq.isEmpty()) {
197+
const [topEdgwWt, currNode] = pq.dequeue().element;
198+
199+
if (vis[currNode]) continue;
200+
vis[currNode] = true;
201+
cost += topEdgwWt;
202+
203+
for (const [adjPoint, edWt] of adj[currNode]) {
204+
if (!vis[adjPoint]) {
205+
pq.enqueue([edWt, adjPoint]);
206+
}
207+
}
208+
}
209+
210+
return cost;
211+
}
212+
}
213+
214+
```
215+
</TabItem>
216+
<TabItem value="Python" label="Python">
217+
<SolutionAuthor name="@hiteshgahanolia"/>
218+
```python
219+
import heapq
220+
221+
class Solution:
222+
def manhattDist(self, v1, v2):
223+
return abs(v1[0] - v2[0]) + abs(v1[1] - v2[1])
224+
225+
def minCostConnectPoints(self, points):
226+
n = len(points)
227+
adj = [[] for _ in range(n)]
228+
229+
for i in range(n):
230+
for j in range(i + 1, n):
231+
dist = self.manhattDist(points[i], points[j])
232+
adj[i].append((j, dist))
233+
adj[j].append((i, dist))
234+
235+
pq = [(0, 0)] # (distance, point)
236+
vis = [False] * n
237+
cost = 0
238+
239+
while pq:
240+
topEdgwWt, currNode = heapq.heappop(pq)
241+
242+
if vis[currNode]:
243+
continue
244+
vis[currNode] = True
245+
cost += topEdgwWt
246+
247+
for adjPoint, edWt in adj[currNode]:
248+
if not vis[adjPoint]:
249+
heapq.heappush(pq, (edWt, adjPoint))
250+
251+
return cost
252+
253+
```
254+
255+
</TabItem>
256+
<TabItem value="Java" label="Java">
257+
<SolutionAuthor name="@hiteshgahanolia"/>
258+
```java
259+
import java.util.*;
260+
261+
class Solution {
262+
private int manhattDist(int[] v1, int[] v2) {
263+
return Math.abs(v1[0] - v2[0]) + Math.abs(v1[1] - v2[1]);
264+
}
265+
266+
public int minCostConnectPoints(int[][] points) {
267+
int n = points.length;
268+
List<List<int[]>> adj = new ArrayList<>();
269+
270+
for (int i = 0; i < n; i++) {
271+
adj.add(new ArrayList<>());
272+
}
273+
274+
for (int i = 0; i < n; i++) {
275+
for (int j = i + 1; j < n; j++) {
276+
int dist = manhattDist(points[i], points[j]);
277+
adj.get(i).add(new int[]{j, dist});
278+
adj.get(j).add(new int[]{i, dist});
279+
}
280+
}
281+
282+
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
283+
boolean[] vis = new boolean[n];
284+
pq.add(new int[]{0, 0}); // {distance, point}
285+
int cost = 0;
286+
287+
while (!pq.isEmpty()) {
288+
int[] curr = pq.poll();
289+
int topEdgwWt = curr[0];
290+
int currNode = curr[1];
291+
292+
if (vis[currNode]) continue;
293+
vis[currNode] = true;
294+
cost += topEdgwWt;
295+
296+
for (int[] neighbor : adj.get(currNode)) {
297+
int adjPoint = neighbor[0];
298+
int edWt = neighbor[1];
299+
if (!vis[adjPoint]) {
300+
pq.add(new int[]{edWt, adjPoint});
301+
}
302+
}
303+
}
304+
305+
return cost;
306+
}
307+
}
308+
309+
```
310+
311+
312+
</TabItem>
313+
<TabItem value="C++" label="C++">
314+
<SolutionAuthor name="@hiteshgahanolia"/>
315+
```cpp
316+
class Solution {
317+
public:
318+
int manhattDist(vector<int>&v1 , vector<int>&v2)
319+
{
320+
return abs(abs(v1[0]-v2[0]) + abs(v1[1]-v2[1]));
321+
}
322+
int minCostConnectPoints(vector<vector<int>>& points) {
323+
int n = points.size();
324+
vector<pair<int,int>> adj[n]; //{point , cost or Manhattan dist}
325+
326+
//we have to make a adjacency list fom every point to every other point
327+
for(int i=0; i<n ; i++)
328+
{
329+
for(int j=i+1;j<n ; j++)
330+
{
331+
adj[i].push_back({j , manhattDist(points[i] , points[j])});
332+
adj[j].push_back({i , manhattDist(points[i] , points[j])});
333+
}
334+
}
335+
336+
priority_queue<pair<int,int> , vector<pair<int,int>> , greater<pair<int,int>> > pq;
337+
// {distance , point}
338+
vector<int> vis(n,0);
339+
pq.push({0,0}); //starting from 0 as source
340+
int Cost=0;
341+
while(!pq.empty())
342+
{
343+
auto it = pq.top();
344+
pq.pop();
345+
int CurrNode = it.second ;
346+
int topEdgwWt = it.first;
347+
348+
if(vis[CurrNode]==1) continue;
349+
350+
vis[CurrNode]=1;
351+
352+
Cost+=topEdgwWt;
353+
for(auto it: adj[CurrNode])
354+
{
355+
int adjPoint=it.first;
356+
int edWt=it.second;
357+
if(!vis[adjPoint])
358+
{
359+
pq.push({edWt , adjPoint});
360+
}
361+
}
362+
}
363+
return Cost;
364+
}
365+
};
366+
```
367+
</TabItem>
368+
</Tabs>
369+
370+
</TabItem>
371+
</Tabs>
372+
373+
## References
374+
375+
- **LeetCode Problem**: [ Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/description/)
376+
377+
- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/min-cost-to-connect-all-points/description/)
378+

0 commit comments

Comments
 (0)