【Python資料結構與演算法】【劍指offer】順時針列印矩陣
阿新 • • 發佈:2018-11-26
題目描述與連結:
- 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]