1. 程式人生 > >【Python資料結構與演算法】【劍指offer】順時針列印矩陣

【Python資料結構與演算法】【劍指offer】順時針列印矩陣

題目描述與連結:

思路:

    “魔方轉圈”的思路。將矩陣輸出列印第一行,然後向左滾動一下,再輸出列印第一行,以此類推

 

程式碼:

# -*- 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]