-
Notifications
You must be signed in to change notification settings - Fork 0
/
diagonal-traverse.py
49 lines (44 loc) · 1.09 KB
/
diagonal-traverse.py
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
class Solution:
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return []
x = 0
y = 0
go_up = True
M = len(matrix)
N = len(matrix[0])
count = 0
total_count = M * N
ans = []
while True:
if go_up:
i = -1
j = 1
else:
i = 1
j = -1
while True:
ans.append(matrix[x][y])
count += 1
if not (0 <= x + i < M and 0 <= y + j < N):
break
x += i
y += j
if count == total_count:
break
if go_up:
if y + 1 < N:
y += 1
elif x + 1 < M:
x += 1
else:
if x + 1 < M:
x += 1
elif y + 1 < N:
y += 1
go_up = not go_up
return ans