Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Connecting Cities With Minimum Cost in Pytho
Connecting cities with minimum cost is a classic Minimum Spanning Tree (MST) problem. Given N cities and connections with costs, we need to find the minimum cost to connect all cities. This can be solved using Kruskal's algorithm with a Union-Find data structure.
Problem Understanding
We have N cities numbered from 1 to N, and connections where each connection [city1, city2, cost] represents the cost to connect two cities. We need to find the minimum cost to ensure every pair of cities has a path between them ?
Algorithm Steps
The solution uses Kruskal's algorithm with Union-Find:
Sort all connections by cost in ascending order
Use Union-Find to detect cycles and merge components
Add edges with minimum cost that don't create cycles
Continue until all cities are connected
Implementation
class Solution:
def find(self, x):
"""Find root of element x with path compression"""
if self.parent[x] == -1:
return x
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
"""Union two sets containing x and y"""
parent_x = self.find(x)
parent_y = self.find(y)
if parent_x == parent_y:
return
self.parent[parent_y] = parent_x
def minimumCost(self, n, connections):
"""Find minimum cost to connect all cities"""
self.parent = [-1 for i in range(n + 1)]
remaining_edges = n - 1 # Need n-1 edges for MST
total_cost = 0
# Sort connections by cost
connections.sort(key=lambda x: x[2])
for connection in connections:
city1, city2, cost = connection
# If cities are not connected, connect them
if self.find(city1) != self.find(city2):
self.union(city1, city2)
total_cost += cost
remaining_edges -= 1
# If all cities connected, return cost
if remaining_edges == 0:
return total_cost
# If not all cities can be connected
return -1
# Example usage
solution = Solution()
# Test case 1: Cities can be connected
print(solution.minimumCost(3, [[1,2,5], [1,3,6], [2,3,1]]))
# Test case 2: All cities already connected optimally
print(solution.minimumCost(4, [[1,2,3], [3,4,4]]))
6 -1
How It Works
The algorithm works by:
Sorting: Connections are sorted by cost to always consider cheapest options first
Union-Find: Tracks which cities are already connected to avoid cycles
Greedy Selection: Adds the cheapest edge that connects two separate components
Early Termination: Stops when all cities are connected (n-1 edges added)
Time and Space Complexity
| Aspect | Complexity | Reason |
|---|---|---|
| Time | O(E log E) | Sorting connections dominates |
| Space | O(N) | Parent array for Union-Find |
Where E is the number of connections and N is the number of cities.
Conclusion
This problem demonstrates Kruskal's algorithm for finding Minimum Spanning Trees. The Union-Find data structure efficiently detects cycles while the greedy approach ensures optimal cost selection.
