-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path498-Diagonal-Traverse.js
46 lines (42 loc) · 1.18 KB
/
498-Diagonal-Traverse.js
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
/**
* @param {number[][]} matrix
* @return {number[]}
*/
const findDiagonalOrder = (matrix) => {
if (matrix.length === 0) return matrix;
const row = matrix.length;
const column = matrix[0].length;
const elements = row * column;
const result = [];
let currentRow = 0,
currentColumn = 0;
let movingUp = true;
while (result.length < elements) {
const current = matrix[currentRow][currentColumn];
result.push(current);
if (movingUp) {
if (currentColumn === column - 1) {
movingUp = false;
currentRow++;
} else if (currentRow === 0) {
movingUp = false;
currentColumn++;
} else {
currentRow--;
currentColumn++;
}
} else {
if (currentRow === row - 1) {
movingUp = true;
currentColumn++;
} else if (currentColumn === 0) {
movingUp = true;
currentRow++; // go up one row
} else {
currentRow++;
currentColumn--;
}
}
}
return result;
};