LeetCode: Map Of Highest Peak Solution

1/**
2 * @param {number[][]} isWater
3 * @return {number[][]}
4 */
5var highestPeak = function (isWater) {
6 const [M, N] = [isWater.length, isWater[0].length]
7 const visited = Array.from({ length: M }, _ => Array(N).fill(false))
8 const res = Array.from({ length: M }, _ => Array(N).fill(0))
9
10 let queue = isWater
11 .flatMap((row, i) => row.map((col, j) => [i, j]))
12 .filter(([i, j]) => isWater[i][j])
13 queue.forEach(([i, j]) => (visited[i][j] = true))
14
15 let height = 0
16 while (queue.length) {
17 let temp = []
18
19 for (const [i, j] of queue) {
20 res[i][j] = height
21 for (const [adjacentI, adjacentJ] of [
22 [i - 1, j],
23 [i + 1, j],
24 [i, j - 1],
25 [i, j + 1],
26 ]) {
27 if (
28 0 <= adjacentI &&
29 adjacentI < M &&
30 0 <= adjacentJ &&
31 adjacentJ < N &&
32 !visited[adjacentI][adjacentJ]
33 ) {
34 visited[adjacentI][adjacentJ] = true
35 temp.push([adjacentI, adjacentJ])
36 }
37 }
38 }
39
40 queue = temp
41 height++
42 }
43
44 return res
45}

Comments

Loading comments...

Tags

leetcode

graph

bfs

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Form Array By Concatenating Subarrays Of Another Array

Feb 21, 2021

Previous Post

HoningJS

Search Posts