题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
res = []
n = len(matrix)
if n==0:
return res
left = 0
right = len(matrix[0])-1
top = 0
bottom = n-1
while left<=right and top <=bottom:
# 上边界从左到右
for i in range(left,right+1):
res.append(matrix[top][i])
# 上边界向下
top+=1
if top>bottom:
break
# 右边界从上到下
for i in range(top,bottom+1):
res.append(matrix[i][right])
# 右边界向左
right -=1
if right < left:
break
for i in range(right,left-1,-1):
res.append(matrix[bottom][i])
# 下边界向上
bottom-=1
if bottom<top:
break
# 左边界从下到上
for i in range(bottom,top-1,-1):
res.append(matrix[i][left])
left +=1
if left>right:
break
return res