Skip to content

Commit 5ae3baf

Browse files
authored
Merge pull request #855 from vfonic/1584-Min-Cost-to-Connect-all-Points
Create 1584-Min-Cost-to-Connect-all-Points.rb
2 parents 6628367 + 8db416f commit 5ae3baf

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# @param {Integer[][]} points
2+
# @return {Integer}
3+
def min_cost_connect_points(points)
4+
manhattan = ->(x, y) { (x[0] - y[0]).abs + (x[1] - y[1]).abs }
5+
6+
to_visit = Set.new(points)
7+
8+
result = 0
9+
bil = 1_000_000_000
10+
cost_to = Hash.new { bil }
11+
12+
current_point = points[0]
13+
to_visit.delete current_point
14+
15+
(points.size - 1).times do |_i|
16+
min = bil
17+
next_point = nil
18+
19+
to_visit.each do |point|
20+
cost_to[point] = [cost_to[point], manhattan.call(current_point, point)].min
21+
if min > cost_to[point]
22+
min = cost_to[point]
23+
next_point = point
24+
end
25+
end
26+
27+
current_point = next_point
28+
result += min
29+
to_visit.delete current_point
30+
end
31+
32+
result
33+
end

0 commit comments

Comments
 (0)