Functional JavaScript 1-liner 2-way pass beats 100%
IntuitionFirst assign land cells with large value and water with 0.Next going from bottom right corner update each cell based on neighboring cells to the bottom
# Intuition
First assign land cells with large value and water with 0.

Next going from bottom right corner update each cell based on neighboring cells to the bottom and to the right.

Finally going from top left corner update each cell based on neighboring cells above and to the left.

**Update**: Adding conventional imperative code here, which should be more familiar to most people.

[Faster, space optimized solution](https://leetcode.com/problems/map-of-highest-peak/solutions/6316707/functional-javascript-optimal-solution-o-9pd9)

``` Functional []
highestPeak = g => g
    .map(r => r.map(x => x ? 0 : 1e9))
    .reverse()
    .map(r => g = r.reverse().map((x, j) => r = Math.min(x - 1, r, g[j] ?? 1e9) + 1, r = 1e9), g = [])
    .reverse()
    .map(r => g = r.reverse().map((x, j) => r = Math.min(x - 1, r, g[j] ?? 1e9) + 1, r = 1e9), g = [])
```
``` Imperative []
function highestPeak(isWater: number[][]): number[][] {
    const result: number[][] = isWater
        .map(row => row.map(x => x ? 0 : 1e9));

    const m = isWater.length;
    const n = isWater[0].length

    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; ++j) {
            result[i][j] = Math.min(
                result[i][j] - 1,
                result[i][j - 1] ?? 1e9,
                result[i - 1]?.[j] ?? 1e9,
            ) + 1;
        }
    }

    for (let i = m - 1; i > -1; --i) {
        for (let j = n - 1; j > -1; --j) {
            result[i][j] = Math.min(
                result[i][j] - 1,
                result[i][j + 1] ?? 1e9,
                result[i + 1]?.[j] ?? 1e9,
            ) + 1;
        }
    }

    return result;
};
```

Time: $$O(m*n)$$
Space: $$O(m*n)$$

![Screenshot 2025-01-21 at 5.42.13 PM.png](https://assets.leetcode.com/users/images/cd7425f3-16ea-497a-97aa-daf55ba3d4e2_1737510183.1172504.png)

['Breadth-First Search', 'JavaScript']