Diagonal Traverse LeetCode solution in JavaScript

1
var findDiagonalOrder = function (matrix) {
2
const res = [];
3
for (
4
let r = 0,
5
c = 0,
6
d = 1,
7
i = 0,
8
len = matrix.length * (matrix[0] || []).length;
9
i < len;
10
i++
11
) {
12
res.push(matrix[r][c]);
13
r -= d;
14
c += d;
15
if (!matrix[r] || matrix[r][c] === undefined) {
16
// We've fallen off the...
17
if (d === 1) {
18
if (matrix[r + 1] && matrix[r + 1][c] !== undefined) {
19
// ...top cliff
20
r++;
21
} else {
22
// ...right cliff
23
r += 2;
24
c--;
25
}
26
} else {
27
if (matrix[r] && matrix[r][c + 1] !== undefined) {
28
// ...left cliff
29
c++;
30
} else {
31
// ...bottom cliff
32
r--;
33
c += 2;
34
}
35
}
36
d = -d;
37
}
38
}
39
return res;
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0