leeetcode 剑指 Offer 29. 顺时针打印矩阵

题目

思路:

 

 

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        result = []
        if not matrix:
            return []
        up = 0
        down = len(matrix) - 1
        left = 0
        right = len(matrix[0]) - 1
        while True:
            # 从左到右打印
            for i in range(left, right + 1):
                result.append(matrix[up][i])
            up += 1
            if up > down:break

            # 从上到下打印
            for j in range(up, down + 1):
                result.append(matrix[j][right])
            right -= 1
            if left>right:break

            # 从右到左打印
            for k in range(right, left - 1, -1):
                result.append(matrix[down][k])
            down -= 1
            if up > down: break

            # 从下到上打印
            for m in range(down, up - 1, -1):
                result.append(matrix[m][left])
            left += 1
            if right < left: break
        return result

 

posted @ 2021-09-26 16:37  A-inspire  Views(25)  Comments(0Edit  收藏  举报