-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0498-diagonal-traverse.js
More file actions
45 lines (41 loc) · 872 Bytes
/
0498-diagonal-traverse.js
File metadata and controls
45 lines (41 loc) · 872 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* 498. Diagonal Traverse
* https://leetcode.com/problems/diagonal-traverse/
* Difficulty: Medium
*
* Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
*/
/**
* @param {number[][]} mat
* @return {number[]}
*/
var findDiagonalOrder = function(mat) {
const result = new Array(mat.length * mat[0].length);
for (let r = 0, c = 0, d = 1, i = 0; i < mat.length * mat[0].length;) {
result[i++] = mat[r][c];
if (d === 1) {
if (c === mat[0].length - 1) {
r++;
d = -1;
} else if (r === 0) {
c++;
d = -1;
} else {
r--;
c++;
}
} else {
if (r === mat.length - 1) {
c++;
d = 1;
} else if (c === 0) {
r++;
d = 1;
} else {
r++;
c--;
}
}
}
return result;
};