题解 | #顺时针打印矩阵#
顺时针打印矩阵
http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
访问顺序是 左到右,上到下,右到左,下到上;若访问后 边界-1
方法一:利用zip函数
算法过程:
当矩阵不为空时循环:
因为矩阵为list,首先访问第一行数据则可以pop(0)输出第一行数据;
剩余的将其利用zip函数包装,得到相当于矩阵转置后的结果;并反转(因为要先输出原矩阵的最右一列,因此需反转后pop)
class Solution:
def printMatrix(self , matrix: List[List[int]]) -> List[int]:
# write code here
# 访问顺序是 左到右,上到下,右到左,下到上;若访问后 边界-1
res = []
while matrix:
res += matrix.pop(0)
temp = zip(*matrix)
matrix = list(temp)[::-1]
return res
方法二:模拟遍历
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param matrix int整型二维数组
# @return int整型一维数组
#
class Solution:
def printMatrix(self , matrix: List[List[int]]) -> List[int]:
# write code here
# 访问顺序是 左到右,上到下,右到左,下到上;若访问后 边界-1
up, down, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1 # 初始化边界
res = []
while matrix:
for i in range(left, right + 1):
res.append(matrix[up][i]) # 从左到右输出 某行
up += 1 # 上边界向下移动1
if up > down : break
for i in range(up, down + 1):
res.append(matrix[i][right]) # 从最右列 从上到下输出 某列
right -= 1 # 右边界向左移动1
if left > right : break
for i in range(right, left - 1, -1):
res.append(matrix[down][i]) # 从下到上 输出 某列
down -= 1
if up > down: break
for i in range(down, up - 1, -1):
res.append(matrix[i][left])
left += 1
if left > right: break
return res
