顺时针打印矩阵

  • 问题:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

  • 分析:从左向右、从上到下打印,画图分析,考虑边界变化以及结束条件。

    行不变,列变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)
    
posted @ 2020-07-31 21:31  guguda  阅读(96)  评论(0)    收藏  举报