LeetCode: Map Of Highest Peak Solution
1/**2 * @param {number[][]} isWater3 * @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))910 let queue = isWater11 .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))1415 let height = 016 while (queue.length) {17 let temp = []1819 for (const [i, j] of queue) {20 res[i][j] = height21 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] = true35 temp.push([adjacentI, adjacentJ])36 }37 }38 }3940 queue = temp41 height++42 }4344 return res45}
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
Previous Post
LeetCode: Merge Strings Alternately
Feb 21, 2021