1. 程式人生 > 實用技巧 >順時針列印矩陣

順時針列印矩陣

  • 問題:輸入一個矩陣,按照從外向裡以順時針的順序依次打印出每一個數字。

  • 分析:從左向右、從上到下列印,畫圖分析,考慮邊界變化以及結束條件。

    行不變,列變left-->right;列不變,行變top+1-->bottom;

    行不變,列變right-1-->left+1;列不變,行變,bottom-->top+1

    1(top,left) 2 3(top,right)
    8 9 4
    7(bottom,left) 6 5(bottom,right)
  • 解決:

    class Solution:
        def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
            if not matrix or not matrix[0]:
                return []
            res = []
            top, bottom = 0, len(matrix)-1
            left, right = 0, len(matrix[0])-1
            while left <= right and top <= bottom:
                #i:row j:column
                for j in range(left, right+1):
                    res.append(matrix[top][j])
                for i in range(top+1,bottom+1):
                    res.append(matrix[i][right])
                if left < right and top < bottom:
                    for j in range(right-1,left,-1):
                        res.append(matrix[bottom][j])
                    for i in range(bottom,top,-1):
                        res.append(matrix[i][left])
                top,bottom = top+1, bottom-1
                left,right = left+1, right-1
            return res
        #空間複雜度O(1)
        #時間複雜度O(MN)