|
| 1 | +/** |
| 2 | + * 1765. Map of Highest Peak |
| 3 | + * https://leetcode.com/problems/map-of-highest-peak/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer matrix isWater of size m x n that represents a map of land and |
| 7 | + * water cells: |
| 8 | + * - If isWater[i][j] == 0, cell (i, j) is a land cell. |
| 9 | + * - If isWater[i][j] == 1, cell (i, j) is a water cell. |
| 10 | + * |
| 11 | + * You must assign each cell a height in a way that follows these rules: |
| 12 | + * - The height of each cell must be non-negative. |
| 13 | + * - If the cell is a water cell, its height must be 0. |
| 14 | + * - Any two adjacent cells must have an absolute height difference of at most 1. A cell is |
| 15 | + * adjacent to another cell if the former is directly north, east, south, or west of the |
| 16 | + * latter (i.e., their sides are touching). |
| 17 | + * |
| 18 | + * Find an assignment of heights such that the maximum height in the matrix is maximized. |
| 19 | + * |
| 20 | + * Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. |
| 21 | + * If there are multiple solutions, return any of them. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[][]} isWater |
| 26 | + * @return {number[][]} |
| 27 | + */ |
| 28 | +var highestPeak = function(isWater) { |
| 29 | + const map = isWater.map(row => row.map(() => 0)); |
| 30 | + const values = isWater.map((row, i) => { |
| 31 | + return row.map((value, j) => value ? [i, j] : 0); |
| 32 | + }).flat().filter(Boolean); |
| 33 | + |
| 34 | + for (let value = 0; values.length > value;) { |
| 35 | + const [i, j] = values[value++]; |
| 36 | + const level = map[i][j] + 1; |
| 37 | + [[1, 0], [-1, 0], [0, -1], [0, 1]] |
| 38 | + .map(direction => [i + direction[0], j + direction[1]]) |
| 39 | + .filter(([x, y]) => 0 === isWater[x]?.[y] && !map[x][y]) |
| 40 | + .forEach(([x, y]) => (map[x][y] = level, values.push([x, y]))); |
| 41 | + } |
| 42 | + |
| 43 | + return map; |
| 44 | +}; |
0 commit comments