-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZigzagTraverse.java
More file actions
43 lines (42 loc) · 881 Bytes
/
ZigzagTraverse.java
File metadata and controls
43 lines (42 loc) · 881 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
import java.util.*;
class Program {
// O(mn) time | O(mn) space
public static List<Integer> zigzagTraverse(List<List<Integer>> array) {
// Write your code here.
int height = array.size();
int width = array.get(0).size();
List<Integer> output = new ArrayList<Integer>();
boolean isGoingDown = true;
int row = 0;
int col = 0;
while (0 <= row && row < height && 0 <= col && col < width) {
output.add(array.get(row).get(col));
if (isGoingDown) {
if (col == 0 || row == height - 1) {
isGoingDown = false;
if (row == height - 1) {
col++;
} else {
row++;
}
} else {
row++;
col--;
}
} else {
if (row == 0 || col == width - 1) {
isGoingDown = true;
if (col == width - 1) {
row++;
} else {
col++;
}
} else {
row--;
col++;
}
}
}
return output;
}
}