Skip to content

Commit 37c9b59

Browse files
committed
update 1765
1 parent e210468 commit 37c9b59

File tree

1 file changed

+24
-20
lines changed

1 file changed

+24
-20
lines changed
Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,36 @@
11
# @param {Integer[][]} is_water
22
# @return {Integer[][]}
33
def highest_peak(is_water)
4-
r = is_water.size
5-
c = is_water[0].size
6-
result = Array.new(r) { Array.new(c, Float::INFINITY) }
7-
4+
rows = is_water.size
5+
cols = is_water[0].size
6+
heights = Array.new(rows) { Array.new(cols, Float::INFINITY) }
7+
88
queue = []
9-
(0...r).each { |i|
10-
(0...c).each { |j|
11-
if is_water[i][j] == 1
12-
result[i][j] = 0
13-
queue << [i, j]
9+
(0...rows).each { |r|
10+
(0...cols).each { |c|
11+
if is_water[r][c] == 1
12+
queue << [r, c]
13+
heights[r][c] = 0
1414
end
1515
}
1616
}
1717

18-
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
18+
directions = [[-1,0],[1,0],[0,-1],[0,1]].freeze
19+
current_height = 0
1920
until queue.empty?
20-
i, j = queue.shift
21-
directions.each { |dr, dc|
22-
_i = i + dr
23-
_j = j + dc
24-
next if _i < 0 || _i >= r || _j < 0 || _j >= c
25-
26-
queue << [_i, _j] if result[_i][_j] == Float::INFINITY
27-
result[_i][_j] = [result[_i][_j], result[i][j] + 1].min
28-
}
21+
queue.size.times do
22+
r, c = queue.shift
23+
directions.each { |dr, dc|
24+
new_r = r + dr
25+
new_c = c + dc
26+
if new_r >= 0 && new_r < rows && new_c >= 0 && new_c < cols && heights[new_r][new_c] == Float::INFINITY
27+
queue << [new_r, new_c]
28+
heights[new_r][new_c] = current_height + 1
29+
end
30+
}
31+
end
32+
current_height += 1
2933
end
3034

31-
result
35+
heights
3236
end

0 commit comments

Comments
 (0)