AlgoMaster Logo

Min Cost to Connect All Points

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Kruskal's Algorithm with Union-Find

Intuition:

The problem can be translated into finding a Minimum Spanning Tree (MST) of a graph where each point represents a node, and the edges are the Manhattan distance between each pair of points.

Kruskal’s Algorithm is a common approach to solve the MST problem. It sorts all the edges in increasing order of their weights and adds them one by one to the MST if they don’t form a cycle. To check cycles efficiently, we use a Union-Find data structure.

Code:

2. Prim's Algorithm using Priority Queue

Intuition:

Prim's Algorithm grows an MST from a single starting point by adding the cheapest edge to the set of connected points. We can implement this efficiently using a priority queue to always extend MST with the lowest weight edge available.

Code: