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

Cost of connecting two houses is the

Manhattan Distancebetween the two points (x_{i}, y_{i}) and (x_{j}, y_{j}) i.e.,|x, where |p| denotes the absolute value of p._{i}– x_{j}| + |y_{i}– y_{j}|

**Examples:**

Input:houses[][] = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]Output:20Explanation:

Connect house 1 (0, 0) with house 2 (2, 2) with cost = 4

Connect house 2 (2, 2) with house 3 (3, 10) with cost =9

Connect house 2 (2, 2) with house 4 (5, 2) with cost =3

At last, connect house 4 (5, 2) with house 5 (7, 0) with cost 4.

All the houses are connected now.

The overall minimum cost is 4 + 9 + 3 + 4 = 20.

Input:houses[][] = [[3, 12], [-2, 5], [-4, 1]]Output:18Explanation:

Connect house 1 (3, 12) with house 2 (-2, 5) with cost = 12

Connect house 2 (-2, 5) with house 3 (-4, 1) with cost = 6

All the houses are connected now.

The overall minimum cost is 12 + 6 = 18.

**Approach:** The idea is to create a weighted graph from the given information with weights between any pair of edges equal to the cost of connecting them, say **C _{i}** i.e., the Manhattan distance between the two coordinates. Once the graph is generated, apply Kruskal’s Algorithm to find the Minimum Spanning Tree of the graph using Disjoint Set. Finally, print the minimum cost.

Below is the implementation of the above approach:

## C++

`// C++ program for the above approach` `#include <bits/stdc++.h>` `using` `namespace` `std;` `vector<` `int` `> parent, size;` `// Utility function to find set of an` `// element v using path compression` `// technique` `int` `find_set(` `int` `v)` `{` ` ` `// If v is the parent` ` ` `if` `(v == parent[v])` ` ` `return` `v;` ` ` `// Otherwsie, recursively` ` ` `// find its parent` ` ` `return` `parent[v]` ` ` `= find_set(parent[v]);` `}` `// Function to perform union` `// of the sets a and b` `int` `union_sets(` `int` `a, ` `int` `b)` `{` ` ` `// Find parent of a and b` ` ` `a = find_set(a);` ` ` `b = find_set(b);` ` ` `// If parent are different` ` ` `if` `(a != b) {` ` ` `// Swap Operation` ` ` `if` `(size[a] < size[b])` ` ` `swap(a, b);` ` ` `// Update parent of b as a` ` ` `parent[b] = a;` ` ` `size[a] += size[b];` ` ` `return` `1;` ` ` `}` ` ` `// Otherwise, return 0` ` ` `return` `0;` `}` `// Function to create a Minimum Cost` `// Spanning tree for given houses` `void` `MST(` `int` `houses[][2], ` `int` `n)` `{` ` ` `// Stores adjacency list of graph` ` ` `vector<pair<` `int` `, pair<` `int` `, ` `int` `> > > v;` ` ` `// Traverse each coordinate` ` ` `for` `(` `int` `i = 0; i < n; i++) {` ` ` `for` `(` `int` `j = i + 1; j < n; j++) {` ` ` `// Find the Manhattan distance` ` ` `int` `p = ` `abs` `(houses[i][0]` ` ` `- houses[j][0]);` ` ` `p += ` `abs` `(houses[i][1]` ` ` `- houses[j][1]);` ` ` `// Add the edges` ` ` `v.push_back({ p, { i, j } });` ` ` `}` ` ` `}` ` ` `parent.resize(n);` ` ` `size.resize(n);` ` ` `// Sort all the edges` ` ` `sort(v.begin(), v.end());` ` ` `// Initialize parent[] and size[]` ` ` `for` `(` `int` `i = 0; i < n; i++) {` ` ` `parent[i] = i, size[i] = 1;` ` ` `}` ` ` `/// Stores the minimum cost` ` ` `int` `ans = 0;` ` ` `// Finding the minimum cost` ` ` `for` `(` `auto` `x : v) {` ` ` `// Perform the unioun operation` ` ` `if` `(union_sets(x.second.first,` ` ` `x.second.second)) {` ` ` `ans += x.first;` ` ` `}` ` ` `}` ` ` `// Print the minimum cost` ` ` `cout << ans;` `}` `// Driver Code` `int` `main()` `{` ` ` `// Given houses` ` ` `int` `houses[][2] = { { 0, 0 }, { 2, 2 }, ` ` ` `{ 3, 10 }, { 5, 2 }, ` ` ` `{ 7, 0 }};` ` ` `int` `N = ` `sizeof` `(houses)` ` ` `/ ` `sizeof` `(houses[0]);` ` ` `// Function Call` ` ` `MST(houses, N);` ` ` `return` `0;` `}` |

*chevron_right*

*filter_none*

## Python3

`# Python3 program for the above approach` `parent ` `=` `[` `0` `] ` `*` `100` `size ` `=` `[` `0` `] ` `*` `100` `# Utility function to find set of an` `# element v using path compression` `# technique` `def` `find_set(v):` ` ` ` ` `# If v is the parent` ` ` `if` `(v ` `=` `=` `parent[v]):` ` ` `return` `v` ` ` `# Otherwsie, recursively` ` ` `# find its parent` ` ` `parent[v] ` `=` `find_set(parent[v])` ` ` `return` `parent[v]` `# Function to perform union` `# of the sets a and b` `def` `union_sets(a, b):` ` ` ` ` `# Find parent of a and b` ` ` `a ` `=` `find_set(a)` ` ` `b ` `=` `find_set(b)` ` ` `# If parent are different` ` ` `if` `(a !` `=` `b):` ` ` ` ` `# Swap Operation` ` ` `if` `(size[a] < size[b]):` ` ` `a, b ` `=` `b, a` ` ` `# Update parent of b as a` ` ` `parent[b] ` `=` `a` ` ` `size[a] ` `+` `=` `size[b]` ` ` `return` `1` ` ` `# Otherwise, return 0` ` ` `return` `0` `# Function to create a Minimum Cost` `# Spanning tree for given houses` `def` `MST(houses, n):` ` ` ` ` `# Stores adjacency list of graph` ` ` `v ` `=` `[]` ` ` `# Traverse each coordinate` ` ` `for` `i ` `in` `range` `(n):` ` ` `for` `j ` `in` `range` `(i ` `+` `1` `, n):` ` ` `# Find the Manhattan distance` ` ` `p ` `=` `abs` `(houses[i][` `0` `] ` `-` ` ` `houses[j][` `0` `])` ` ` `p ` `+` `=` `abs` `(houses[i][` `1` `] ` `-` ` ` `houses[j][` `1` `])` ` ` `# Add the edges` ` ` `v.append([p, i, j])` ` ` `# Sort all the edges` ` ` `v ` `=` `sorted` `(v)` ` ` `# Initialize parent[] and size[]` ` ` `for` `i ` `in` `range` `(n):` ` ` `parent[i] ` `=` `i` ` ` `size[i] ` `=` `1` ` ` `# Stores the minimum cost` ` ` `ans ` `=` `0` ` ` `# Finding the minimum cost` ` ` `for` `x ` `in` `v:` ` ` `# Perform the unioun operation` ` ` `if` `(union_sets(x[` `1` `], x[` `2` `])):` ` ` `ans ` `+` `=` `x[` `0` `]` ` ` ` ` `# Print the minimum cost` ` ` `print` `(ans)` `# Driver Code` `if` `__name__ ` `=` `=` `'__main__'` `:` ` ` ` ` `# Given houses` ` ` `houses ` `=` `[ [ ` `0` `, ` `0` `], [ ` `2` `, ` `2` `],` ` ` `[ ` `3` `, ` `10` `], [ ` `5` `, ` `2` `],` ` ` `[ ` `7` `, ` `0` `] ]` ` ` `N ` `=` `len` `(houses)` ` ` `# Function Call` ` ` `MST(houses, N)` `# This code is contributed by mohit kumar 29` |

*chevron_right*

*filter_none*

**Output:**

20

**Time Complexity:** O(N^{2})**Auxiliary Space:** O(N^{2})

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Minimum broadcast range required by M towers to reach N houses
- Minimum cost to connect all cities
- Connect n ropes with minimum cost
- Minimum cost to connect weighted nodes represented as array
- Find maximum possible stolen value from houses
- Minimum cost required to convert all Subarrays of size K to a single element
- Minimum cost required to move all elements to the same position
- Minimum Cost using Dijkstra by reducing cost of an Edge
- Minimum cost to empty Array where cost of removing an element is 2^(removed_count) * arr[i]
- Find maximum distance between any city and station
- Minimum Cost required to generate a balanced Bracket Sequence
- Minimum cost required to rearrange a given array to make it equal to another given array
- Minimum cost of flipping characters required to convert Binary String to 0s only
- Count of minimum reductions required to get the required sum K
- Cost required to empty a given array by repeated removal of maximum obtained by given operations
- Minimum cost for acquiring all coins with k extra coins allowed with every coin
- Find minimum cost to buy all books
- Minimum cost to equal all elements of array using two operation
- Minimum cost to make all array elements equal
- Minimum cost to merge all elements of List

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.