bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1135. Connecting Cities With Minimum Cost

1135. Connecting Cities With Minimum Cost

Leetcode Solutions

Minimum Spanning Tree (Using Kruskal's algorithm)

  1. Sort the connections array based on the cost in ascending order.
  2. Initialize a Disjoint Set Union-Find structure with each city as a separate set.
  3. Iterate over the sorted connections.
  4. For each connection, use the Union-Find structure to check if the cities are already connected.
  5. If they are not connected, union them and add the cost to the total cost.
  6. Keep track of the number of edges added to the MST.
  7. If the number of edges added equals n - 1, all cities are connected, and we return the total cost.
  8. If we finish iterating through connections without connecting all cities, return -1.
UML Thumbnail

Minimum Spanning Tree (Using Prim's algorithm)

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...