题目描述与链接:
- https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
- 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
思路:
“魔方转圈”的思路。将矩阵输出打印第一行,然后向左滚动一下,再输出打印第一行,以此类推
代码:
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
if not matrix:
return []
result = []
for i in matrix.pop(0):
result.append(i)
while matrix:
matrix = self.transposeM(matrix)
for i in matrix.pop(0):
result.append(i)
return result
def transposeM(self,matrix):
m = len(matrix)
n = len(matrix[0])
res = []
for i in range(n):
row = []
for j in range(m):
row.append(matrix[j][n-i-1])
res.append(row)
return res
结果:
>>> qq = [[1,2],[3,4]]
ss1 = Solution()
ss1.printMatrix(qq)
>>> [1, 2, 4, 3]
>>> ee = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
ss2 = Solution()
ss2.printMatrix(ee)
>>> [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]