As Far from Land as Possible LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} grid
3
* @return {number}
4
*/
5
const DIR = [
6
[0, 1],
7
[0, -1],
8
[1, 0],
9
[-1, 0],
10
];
11
var maxDistance = function (grid) {
12
const ROWS = grid.length;
13
const COLS = grid[0].length;
14
const cost = new Array(ROWS).fill().map(() => new Array(COLS).fill(Infinity));
15
const que = [];
16
for (let row = 0; row < ROWS; row++) {
17
for (let col = 0; col < COLS; col++) {
18
if (grid[row][col] === 1) {
19
que.push([row, col]);
20
cost[row][col] = 0;
21
}
22
}
23
}
24
if (que.length == 0 || que.length == ROWS * COLS) return -1;
25
while (que.length) {
26
const [row, col] = que.shift();
27
for (const dir of DIR) {
28
const newRow = row + dir[0];
29
const newCol = col + dir[1];
30
if (newRow < 0 || newCol < 0 || newRow >= ROWS || newCol >= COLS)
31
continue;
32
if (cost[newRow][newCol] > cost[row][col] + 1) {
33
cost[newRow][newCol] = cost[row][col] + 1;
34
que.push([newRow, newCol]);
35
}
36
}
37
}
38
let max = 0;
39
for (const row of cost) {
40
max = Math.max(max, ...row);
41
}
42
return max;
43
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0