Get Biggest Three Rhombus Sums in a Grid LeetCode solution in JavaScript

1
var getBiggestThree = function (grid) {
2
const m = grid.length;
3
const n = grid[0].length;
4

5
const set = new Set();
6

7
for (let i = 0; i < m; ++i) {
8
for (let j = 0; j < n; ++j) {
9
let sum = grid[i][j];
10

11
set.add(sum);
12

13
let len = 1;
14
let row = i;
15
let col = j;
16

17
while (withinBound(row + 1, col - 1)) {
18
++len;
19
++row;
20
--col;
21

22
traverse(i, j, row, col, sum, len, 0, "botRight");
23
sum += grid[row][col];
24
}
25
}
26
}
27

28
let max1;
29
let max2;
30
let max3;
31

32
for (const num of set) {
33
if (max1 == null || num > max1) {
34
max3 = max2;
35
max2 = max1;
36
max1 = num;
37
} else if (max2 == null || num > max2) {
38
max3 = max2;
39
max2 = num;
40
} else if (max3 == null || num > max3) {
41
max3 = num;
42
}
43
}
44

45
const res = [];
46

47
if (max1) res[0] = max1;
48
if (max2) res[1] = max2;
49
if (max3) res[2] = max3;
50

51
return res;
52

53
function traverse(
54
destRow,
55
destCol,
56
currRow,
57
currCol,
58
totSum,
59
lenSize,
60
currLen,
61
currDir
62
) {
63
if (currRow === destRow && currCol === destCol) {
64
set.add(totSum);
65
return;
66
}
67

68
totSum += grid[currRow][currCol];
69
++currLen;
70

71
if (currDir === "botRight") {
72
if (currLen < lenSize) {
73
if (!withinBound(currRow + 1, currCol + 1)) return;
74

75
traverse(
76
destRow,
77
destCol,
78
currRow + 1,
79
currCol + 1,
80
totSum,
81
lenSize,
82
currLen,
83
currDir
84
);
85
} else if (currLen === lenSize) {
86
if (!withinBound(currRow - 1, currCol + 1)) return;
87

88
traverse(
89
destRow,
90
destCol,
91
currRow - 1,
92
currCol + 1,
93
totSum,
94
lenSize,
95
1,
96
"topRight"
97
);
98
}
99
} else if (currDir === "topRight") {
100
if (currLen < lenSize) {
101
if (!withinBound(currRow - 1, currCol + 1)) return;
102

103
traverse(
104
destRow,
105
destCol,
106
currRow - 1,
107
currCol + 1,
108
totSum,
109
lenSize,
110
currLen,
111
"topRight"
112
);
113
} else if (currLen === lenSize) {
114
if (!withinBound(currRow - 1, currCol - 1)) return;
115

116
traverse(
117
destRow,
118
destCol,
119
currRow - 1,
120
currCol - 1,
121
totSum,
122
lenSize,
123
1,
124
"topLeft"
125
);
126
}
127
} else if (currDir === "topLeft") {
128
if (!withinBound(currRow - 1, currCol - 1)) return;
129

130
traverse(
131
destRow,
132
destCol,
133
currRow - 1,
134
currCol - 1,
135
totSum,
136
lenSize,
137
currLen,
138
"topLeft"
139
);
140
}
141
}
142

143
function withinBound(row, col) {
144
return row >= 0 && col >= 0 && row < m && col < n;
145
}
146
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0