Linjiayu6 / LeetCode

[2019+] CS Fundamentals: Algorithms and Data structures
0 stars 0 forks source link

[矩阵] #7

Open Linjiayu6 opened 4 years ago

Linjiayu6 commented 4 years ago

1 - 打印矩阵

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

54. 螺旋矩阵

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        m = len(matrix)
        if m == 0: return []
        if m == 1: return matrix[0] # 矩阵只有一行
        if m == 2: return matrix[0] + matrix[1][::-1] # 矩阵只有两行

        if len(matrix[0]) == 0: return [] # 矩阵一行里没有值
        if len(matrix[0]) == 1: # 矩阵一行里只有一个值
            result = []
            for m in matrix:
                result += m
            return result

        up = matrix.pop(0) # 第一个
        bottom = matrix.pop() # pop最后一个
        left, right = [], []
        for i in range(len(matrix)):
                left.append(matrix[i].pop(0))
                right.append(matrix[i].pop())

        # [::-1] 数组逆序
        return up + right + bottom[::-1] + left[::-1] + self.spiralOrder(matrix)