Largest Plus Sign LeetCode solution in JavaScript

1
/**
2
* @param {number} n
3
* @param {number[][]} mines
4
* @return {number}
5
*/
6
var orderOfLargestPlusSign = function (n, mines) {
7
// create n * n as a table, and each grid fill the maximum number
8
const t = new Array(n).fill(0).map(() => new Array(n).fill(n));
9

10
// insert `0` to the grid in table according the position in mines
11
mines.forEach((a) => (t[a[0]][a[1]] = 0));
12

13
// loop each rows and cols
14
// - for rows: calculate non-zero grid from left to right
15
// - for cols: calculate non-zero grid from top to bottom
16
// - when the loop is completed, all of non-zero values will be calculated by four directions
17
// - and these grids value will be updated by comparing. then we can obtain the minimum value of the four directions caculation, which is the maximum of the grid
18
for (let i = 0; i < n; i++) {
19
// save the maximum value of non-zeros with for directions
20
let [l, r, u, d] = [0, 0, 0, 0];
21

22
// l: left, loop row i from left to right
23
// r: right, loop row i from right to left
24
// u: up, loop col i from top to bottom
25
// d: down, loop col i from bottom to top
26
for (let j = 0, k = n - 1; j < n; j++, k--) {
27
// if the value is `0`, then set variable to `0`, and indicates it's broken
28
l = t[i][j] && l + 1;
29
r = t[i][k] && r + 1;
30
u = t[j][i] && u + 1;
31
d = t[k][i] && d + 1;
32

33
// if current value is less than origin value
34
// one possibility: the origin value is default
35
// another possibility: the length of non-zero in a centain direction is langer than in the current direction, which the minimum value we need
36
if (l < t[i][j]) t[i][j] = l;
37
if (r < t[i][k]) t[i][k] = r;
38
if (u < t[j][i]) t[j][i] = u;
39
if (d < t[k][i]) t[k][i] = d;
40
}
41
}
42

43
// return maximum value be saved by all cells
44
return Math.max(...t.map((v) => Math.max(...v)));
45
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0