Skip to content

Commit d2a627f

Browse files
committed
矩阵的之字型遍历
1 parent b74666c commit d2a627f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

matrix_zigzag_traversal.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param: a matrix of integers
5+
# @return: a list of integers
6+
def printZMatrix(self, matrix):
7+
# write your code here
8+
ret = []
9+
if matrix:
10+
rows, cols = len(matrix), len(matrix[0])
11+
i, count = 1, rows * cols
12+
row, col = 0, 0
13+
ret.append(matrix[0][0])
14+
while i < count:
15+
if col < (cols - 1): # 向右
16+
col += 1
17+
ret.append(matrix[row][col])
18+
elif row < (rows - 1): # 不能向右就向下
19+
row += 1
20+
ret.append(matrix[row][col])
21+
i += 1
22+
while (i < count) and (row < (rows - 1)) and (col > 0): # 左下
23+
row += 1
24+
col -= 1
25+
ret.append(matrix[row][col])
26+
i += 1
27+
if (i < count) and (row < (rows - 1)): # 向下
28+
row += 1
29+
ret.append(matrix[row][col])
30+
elif (i < count) and (col < (cols - 1)): # 向右
31+
col += 1
32+
ret.append(matrix[row][col])
33+
i += 1
34+
while (i < count) and (row > 0) and (col < (cols - 1)): # 左上
35+
row -= 1
36+
col += 1
37+
ret.append(matrix[row][col])
38+
i += 1
39+
return ret

0 commit comments

Comments
 (0)