Skip to content

Commit 8976bea

Browse files
authored
Merge pull request #1503 from Hitesh4278/min-cost-to-connect-all-points
Added Solution of Min cost to connect all points - Issue No - 1440
2 parents 331e17a + d98d0d7 commit 8976bea

File tree

2 files changed

+377
-1
lines changed

2 files changed

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

0 commit comments

Comments
 (0)