forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix_zigzag_traversal.py
More file actions
39 lines (38 loc) · 1.42 KB
/
matrix_zigzag_traversal.py
File metadata and controls
39 lines (38 loc) · 1.42 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
# -*- coding: utf-8 -*-
class Solution:
# @param: a matrix of integers
# @return: a list of integers
def printZMatrix(self, matrix):
# write your code here
ret = []
if matrix:
rows, cols = len(matrix), len(matrix[0])
i, count = 1, rows * cols
row, col = 0, 0
ret.append(matrix[0][0])
while i < count:
if col < (cols - 1): # 向右
col += 1
ret.append(matrix[row][col])
elif row < (rows - 1): # 不能向右就向下
row += 1
ret.append(matrix[row][col])
i += 1
while (i < count) and (row < (rows - 1)) and (col > 0): # 左下
row += 1
col -= 1
ret.append(matrix[row][col])
i += 1
if (i < count) and (row < (rows - 1)): # 向下
row += 1
ret.append(matrix[row][col])
elif (i < count) and (col < (cols - 1)): # 向右
col += 1
ret.append(matrix[row][col])
i += 1
while (i < count) and (row > 0) and (col < (cols - 1)): # 左上
row -= 1
col += 1
ret.append(matrix[row][col])
i += 1
return ret