# 54. 螺旋矩阵(Spiral Matrix)

09/24 00:00

## 54. Spiral Matrix

``输入:``[`` [ 1, 2, 3 ],`` [ 4, 5, 6 ],`` [ 7, 8, 9 ]``]``输出: [1,2,3,6,9,8,7,4,5]``

``输入:``[``  [1, 2, 3, 4],``  [5, 6, 7, 8],``  [9,10,11,12]``]``输出: [1,2,3,4,8,12,11,10,9,5,6,7]``

## 模拟法

O(M*N)

``class Solution:``    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:``        if len(matrix) == 0 or len(matrix[0]) == 0:``            return []``        # 方向数组``        x_directions = [0, 1, 0, -1]``        y_directions = [1, 0, -1, 0]``        shrink_bounds = [1, -1, -1, 1]``        # 上右下左``        bounds = [0, len(matrix[0]) - 1, len(matrix) - 1, 0]``        res = []``        i = j = 0``        res.append(matrix[i][j])``        while bounds[0] <= bounds[2] and bounds[3] <= bounds[1]:``            for k in range(4):``                while bounds[0] <= i + x_directions[k] <= bounds[2] and bounds[3] <= j + y_directions[k] <= bounds[1]:``                    i += x_directions[k]``                    j += y_directions[k]``                    res.append(matrix[i][j])``                bounds[k] += shrink_bounds[k]``        return res``

--End--

0
0 收藏

0 评论
0 收藏
0