Skip to content

Commit

Permalink
Create 1584-min-cost-to-connect-all-points.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a committed Dec 29, 2022
1 parent 324cd74 commit d01c09f
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions kotlin/1584-min-cost-to-connect-all-points.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Solution {
fun minCostConnectPoints(points: Array<IntArray>): Int {
val minHeap = PriorityQueue<Pair<Int,Int>> { a: Pair<Int, Int>, b: Pair<Int, Int> -> a.second - b.second } // sort by distance
val visited = HashSet<Int>()
var minCost = 0
minHeap.add(Pair(0,0))
while(visited.size < points.size){
val (node,cost) = minHeap.poll()
if(visited.contains(node))
continue
minCost += cost
visited.add(node)
for(i in 0..points.size-1){
val (nextX,nextY) = points[i]
val (currentX, CurrentY) = points[node]
val distance = Math.abs(currentX - nextX) + Math.abs(CurrentY - nextY)
minHeap.add(Pair(i,distance))
}
}
return minCost
}
}

0 comments on commit d01c09f

Please sign in to comment.