顺时针打印矩阵
时间限制:1秒 空间限制:32768K 热度指数:441320
本题知识点: 数组
算法知识视频讲解
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
方法1
解析
可以模拟魔方逆时针旋转的方法,一直做取出第一行的操作
例如
1 2 3
4 5 6
7 8 9
输出并删除第一行后,再进行一次逆时针旋转,就变成:
6 9
5 8
4 7
继续重复上述操作即可。
代码
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
ans = []
while matrix:
ans += matrix[0]
matrix.pop(0)
matrix = [[each[i] for each in matrix] for i in range(len(matrix[0]))][::-1]\
if matrix else [] # [::-1]类似于.reverse()
return ans
update:2019年10月5日
方法2
解析
1.按顺序,打印:第一行 -> 最后一列 -> 最后一行 -> 第一列
2.递归打印除去最外一层,剩下的矩阵
代码
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
ans = []
if len(matrix) == 0:
return ans
if len(matrix[0]) == 0:
return ans
# 1.第一行
ans.extend(matrix.pop(0))
if len(matrix) == 0:
return ans
else:
# 2.最后一列
for i in range(0, len(matrix)):
ans.append(matrix[i].pop())
if len(matrix) == 0:
return ans
else:
# 3.最后一行
ans.extend(matrix.pop()[::-1])
if len(matrix) == 0:
return ans
else:
# 4.第一列
for i in range(len(matrix) - 1, -1, -1):
# 这里要判断一下第一列是否为[],由于pop之后会可能有[]存在
if len(matrix[i]):
ans.append(matrix[i].pop(0))
if len(matrix) == 0:
return ans
else:
# 递归打印剩下的矩阵
ans.extend(self.printMatrix(matrix))
return ans