forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiagonal-traverse.py
39 lines (32 loc) · 927 Bytes
/
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
# Time: O(m * n)
# Space: O(1)
class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix or not matrix[0]:
return []
result = []
row, col, d = 0, 0, 0
dirs = [(-1, 1), (1, -1)]
for i in xrange(len(matrix) * len(matrix[0])):
result.append(matrix[row][col])
row += dirs[d][0]
col += dirs[d][1]
if row >= len(matrix):
row = len(matrix) - 1
col += 2
d = 1 - d
elif col >= len(matrix[0]):
col = len(matrix[0]) - 1
row += 2
d = 1 - d
elif row < 0:
row = 0
d = 1 - d
elif col < 0:
col = 0
d = 1 - d
return result