Skip to content

Commit 425ad28

Browse files
committed
Zigzag Traverse
1 parent f11e14b commit 425ad28

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

zigzag_traverse.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Write a function that takes in a two-dimensional array and returns a one-dimensional array of all the array's elements
2+
# in zigzag order. Zigzag order starts at the top left corner of the two-dimensional array, goes down by one element,
3+
# and proceeds in a zigzag pattern all the way to the bottom right corner.
4+
5+
def zigzagTraverse(array):
6+
lin = 0
7+
col = 0
8+
L = len(array) - 1
9+
C = len(array[0]) - 1
10+
is_going_down = True
11+
result = []
12+
while not out_of_bounds(lin, col, array):
13+
result.append(array[lin][col])
14+
if is_going_down:
15+
if col == 0 or lin == L:
16+
is_going_down = False
17+
if lin == L:
18+
col += 1
19+
else:
20+
lin += 1
21+
else:
22+
lin += 1
23+
col -= 1
24+
else:
25+
if lin == 0 or col == C:
26+
is_going_down = True
27+
if col == C:
28+
lin += 1
29+
else:
30+
col += 1
31+
else:
32+
lin -= 1
33+
col += 1
34+
35+
return result
36+
37+
38+
def out_of_bounds(lin, col, array):
39+
L = len(array) - 1
40+
C = len(array[0]) - 1
41+
return lin < 0 or lin > L or col < 0 or col > C
42+
43+
44+
if __name__ == '__main__':
45+
matrix = [
46+
[1, 3, 4, 10],
47+
[2, 5, 9, 11],
48+
[6, 8, 12, 15],
49+
[7, 13, 14, 16]
50+
]
51+
assert zigzagTraverse(matrix) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

0 commit comments

Comments
 (0)