题解 | #顺时针打印矩阵#
顺时针打印矩阵
http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
直接按照题目逻辑去遍历整个矩阵就行了,没什么花里胡哨的想法。 先确定当前点数据结构应该包含哪些信息,显然应该有三个信息,横坐标,纵坐标和移动方向。用x,y和towhere三个变量来保存,并通过修改这三个变量来更新当前位置。用pop函数弹出矩阵中的元素,按照顺序保存到result即可。 towhere值 0,1,2,3 对应 右下左上 注意:pop函数会返回元素值同时还会将该位置元素从矩阵中删除,因此向右和向左移动的过程中,y值不用动。向右移动时y=0,向左移动时y始终是该行最后一个元素的位置
class Solution:
def printMatrix(self, matrix: List[List[int]]) -> List[int]:
#初始化结果和点的数据内容,x为纵坐标,y为横坐标,towhere为移动方向
result = []
x=0
y=0
towhere = 0
#判断matrix不为空
num = len(matrix)*len(matrix[0])
if len(matrix[0]) != 0:
#开始遍历
for i in range(num):
result.append(matrix[x].pop(y))
if i!=num-1:
if towhere == 0 and matrix[x] == [] and x+1<len(matrix):
x+=1
towhere = 1
y=len(matrix[x])-1
elif towhere == 1:
if x+1 < len(matrix) and len(matrix[x+1]) != 0:
x+=1
y=len(matrix[x])-1
else:
towhere=2
y=len(matrix[x])-1
elif towhere == 2:
if len(matrix[x]) == 0:
towhere = 3
x-=1
y=0
else:
y=len(matrix[x])-1
elif towhere == 3:
if x-1>=0:
if matrix[x-1] != []:
x-=1
else:
towhere=0
y=0
else:
towhere = 0
y=0
return result
# 当matrix为空,直接返回空list
else:
return result