-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiagonal-traverse.js
More file actions
48 lines (44 loc) · 874 Bytes
/
diagonal-traverse.js
File metadata and controls
48 lines (44 loc) · 874 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
46
47
48
/**
* @param {number[][]} mat
* @return {number[]}
*/
var findDiagonalOrder = function (mat) {
const m = mat.length - 1;
const n = mat[0].length - 1;
let result = [];
let index = 1;
let row = 0;
let col = 0;
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10,11,12],
];
while (row <= m && col <= n) {
let tempRow = row;
let tempCol = Math.min(col, n);
const temp = [];
// 对角线遍历
while (tempRow <= m && tempCol >= 0) {
temp.push(mat[tempRow][tempCol]);
tempRow++;
tempCol--;
}
if (index % 2 === 0) {
result.push(...temp);
} else {
// 奇数层反转数组
result.push(...temp.reverse());
}
if (col === n) {
row++;
}
if (col < n) {
col++;
}
// 上半部分遍历完后 col = n, col 将保持不变
index++;
}
return result;
};