Leetcode 1584: Min Cost to Connect All Points

grid47
grid47
Exploring patterns and algorithms
Jun 1, 2024 7 min read

You are given a list of points on a 2D plane, represented as coordinates [x, y]. The cost of connecting two points is defined by the Manhattan distance, which is calculated as |xi - xj| + |yi - yj|. Your task is to return the minimum total cost required to connect all the points. A valid connection between points must form a connected graph, where there is exactly one simple path between any two points.
Problem
Approach
Steps
Complexity
Input: You are given an array of points, where each point is represented by a pair of integers: [xi, yi]. The length of the array is at least 1 and at most 1000.
Example: Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Constraints:
• 1 <= points.length <= 1000
• -10^6 <= xi, yi <= 10^6
• All pairs (xi, yi) are distinct.
Output: Return the minimum cost to connect all the points such that the graph formed by the connections is a connected graph with one simple path between any two points.
Example: Output: 20
Constraints:
• The output should be an integer value representing the minimum connection cost.
Goal: The goal is to calculate the minimum cost of connecting all the points using a Minimum Spanning Tree (MST) approach.
Steps:
• 1. Create a list of all possible point connections, each with its corresponding Manhattan distance.
• 2. Sort the connections in increasing order of distance.
• 3. Use a union-find data structure to efficiently group connected points.
• 4. Add connections to the MST, ensuring no cycles are formed, until all points are connected.
Goal: The number of points can be large (up to 1000), so an efficient solution is necessary.
Steps:
• 1 <= points.length <= 1000
• -10^6 <= xi, yi <= 10^6
• All pairs of points are distinct.
Assumptions:
• The points are given in integer coordinates.
• Manhattan distance is used to calculate the cost between two points.
• All points are distinct.
Input: Input: points = [[3,12],[-2,5],[-4,1]]
Explanation: In this case, we need to connect three points on a 2D plane. The cost of connecting them is minimized by choosing the optimal connections, leading to a total cost of 18.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus