Suppose we have an array called points with some points in the form (x, y). Now the cost of connecting two points (xi, yi) and (xj, yj) is the Manhattan distance between them, the formula is |xi - xj| + |yi - yj|. We have to find the minimum cost to make all points connected.
So, if the input is like points = [(0,0),(3,3),(2,10),(6,3),(8,0)], then the output will be 22 because
so here total distance is (6+5+3+8) = 22.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
import heapq def solve(points): points_set = set(range(len(points))) heap = [(0, 0)] visited_node = set() total_distance = 0 while heap and len(visited_node) < len(points): distance, current_index = heapq.heappop(heap) if current_index not in visited_node: visited_node.add(current_index) points_set.discard(current_index) total_distance += distance x0, y0 = points[current_index] for next_index in points_set: x1, y1 = points[next_index] heapq.heappush(heap, (abs(x0 - x1) + abs(y0 - y1), next_index)) return total_distance points = [(0,0),(3,3),(2,10),(6,3),(8,0)] print(solve(points))