-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzigzag-traverse.js
More file actions
54 lines (50 loc) · 1.09 KB
/
zigzag-traverse.js
File metadata and controls
54 lines (50 loc) · 1.09 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
50
51
52
53
54
// Time O(n) where n is the total elements in the 2 dimensional array
// Space O(n)
//zigzag Traverse
function zigzagTraverse(array) {
const height = array.length - 1;
const width = array[0].length - 1;
const result = [];
let row = 0;
let col = 0;
let goingDown = true;
while (!isOutOfBounds(row, col, height, width)) {
result.push(array[row][col]);
if (goingDown) {
if (col === 0 || row === height) {
goingDown = false;
if (row === height) {
col += 1;
} else {
row += 1;
}
} else {
row += 1;
col -= 1;
}
} else {
if (row === 0 || col === width) {
goingDown = true;
if (col === width) {
row += 1;
} else {
col += 1;
}
} else {
row -= 1;
col += 1;
}
}
}
return result;
}
function isOutOfBounds(row, col, height, width) {
return row < 0 || row > height || col < 0 || col > width;
}
const array = [
[1, 3, 4, 10],
[2, 5, 9, 11],
[6, 8, 12, 15],
[7, 13, 14, 16],
];
console.log(zigzagTraverse(array));