-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0498-diagonal-traverse.js
More file actions
49 lines (44 loc) · 1.33 KB
/
0498-diagonal-traverse.js
File metadata and controls
49 lines (44 loc) · 1.33 KB
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
49
/**
* Diagonal Traverse
* Time Complexity: O(m*n)
* Space Complexity: O(m*n)
*/
var findDiagonalOrder = function (mat) {
if (!mat || mat.length === 0 || mat[0].length === 0) {
return [];
}
const numRows = mat.length;
const numCols = mat[0].length;
const totalElements = numRows * numCols;
const traversalResult = new Array(totalElements);
let currentRow = 0;
let currentCol = 0;
let isMovingUpRight = true;
for (let elementCounter = 0; elementCounter < totalElements; elementCounter++) {
traversalResult[elementCounter] = mat[currentRow][currentCol];
if (isMovingUpRight) {
if (currentCol === numCols - 1) {
currentRow++;
isMovingUpRight = false;
} else if (currentRow === 0) {
currentCol++;
isMovingUpRight = false;
} else {
currentRow--;
currentCol++;
}
} else {
if (currentRow === numRows - 1) {
currentCol++;
isMovingUpRight = true;
} else if (currentCol === 0) {
currentRow++;
isMovingUpRight = true;
} else {
currentRow++;
currentCol--;
}
}
}
return traversalResult;
};