Leetcode054 spiral-matrix

螺旋矩阵

题目描述:

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例1

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

示例2

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

解题思路:

  • 整体的算法逻辑是,通过遍历整个矩阵的每一行和每一列,而该遍历的路径是,从第一行从左向右开始,直到末尾,然后向下直到末尾,始终保持一个右→下→左→上的遍历路径,直到遍历完成每一个元素

  • 特别注意三种情况,第一是left == right and top == bottom

    中心剩下一个数值
    ———
    |3|
    ———
    
  • 第二种是top == bottom

    中心横向多个数值
    —————————
    |3 4 5 6|
    —————————
    
  • 第三种是left == right

    中心纵向多个数值
    ———
    |2|
    |3|
    |4|
    ———
    

Python源码:

from typing import List

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []
        left = top = 0
        right = len(matrix[0]) - 1
        bottom = len(matrix) - 1

        result = []
        while left < right and top < bottom:
            for i in range(left, right):
                result.append(matrix[top][i])
            for i in range(top, bottom):
                result.append(matrix[i][right])
            for i in range(right, left, -1):
                result.append(matrix[bottom][i])
            for i in range(bottom, top, -1):
                result.append(matrix[i][left])
            left += 1
            right -= 1
            top += 1
            bottom -= 1
        if left == right and top == bottom:
            result.append(matrix[top][left])
        elif left == right:
            for i in range(top, bottom + 1):
                result.append(matrix[i][left])
        elif top == bottom:
            for i in range(left, right + 1):
                result.append(matrix[top][i])
        return result

欢迎关注我的github:https://github.com/UESTCYangHR

猜你喜欢

转载自blog.csdn.net/dzkdyhr1208/article/details/89449511