VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-cost-required-to-connect-all-houses-in-a-city/

⇱ Minimum cost to connect all houses in a city - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum cost to connect all houses in a city

Last Updated : 28 Mar, 2026

Given a 2D array houses[][] consisting of n 2D coordinates [x, y] where each coordinate represents the location of each house, find the minimum cost to connect all the houses of the city.

Note: Cost of connecting two houses is the Manhattan Distance between the two points (xi, yi) and (xj, yj) i.e., |xi - xj| + |yi - yj|, where |p| denotes the absolute value of p.

Examples:

Input: houses[][] = [[0, 7], [0, 9], [20, 7], [30, 7], [40, 70]]
Output: 105
Explanation:

👁 11

Connect house 1 (0, 7) and house 2 (0, 9) with cost = 2
Connect house 1 (0, 7) and house 3 (20, 7) with cost = 20
Connect house 3 (20, 7) with house 4 (30, 7) with cost = 10 
At last, connect house 4 (30, 7) with house 5 (40, 70) with cost 73.
All the houses are connected now.
The overall minimum cost is 2 + 10 + 20 + 73 = 105.

Input: houses[][] = [[4, 12], [15, 20], [17, 0]]
Output: 41
Explanation:
Connect house 1 (4, 12) and house 2 (15, 20) with cost = 19
Connect house 2 (15, 20) and house 3 (17, 0) with cost = 22
All the houses are connected now.
The overall minimum cost is 19 + 22 = 41.

Using Prim’s Algorithm - Time O(n2 × log(n)) and Space O(n2)

We can think of each house as a node in a graph, and the Manhattan distance between any two houses as the weight of the edge connecting those two nodes. With this interpretation, the problem of connecting all houses with the minimum total cost becomes equivalent to finding a Minimum Spanning Tree (MST) of a complete graph.

Step by Step implementations:

  • Start with any house (we start with house 0).
  • Push all distances from this house to other houses into a min-heap (priority queue).
  • At every step, pick the house with the smallest connection cost that hasn't been visited.
  • Add that cost to the total cost and mark the house as visited.
  • Push distances from this new house to all unvisited houses into the heap.
  • Repeat until all houses are visited and return the total cost.

Output
105

Using Kruskal's Algorithm - Time O(n2 × log(n)) and Space O(n2)

The idea is to treat each house as a node in a complete weighted graph, where the weight between any two houses is given by their Manhattan distance, representing the connection cost. After generating all such edges, we sort them in non-decreasing order and apply Kruskal’s algorithm to build the Minimum Spanning Tree (MST). During this process, a Disjoint Set Union (DSU) structure with path compression and union by rank is used to efficiently track connected components and ensure that no cycles are formed while selecting edges.


Output
105
Comment