leetcode刷题-54螺旋矩阵

题目

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

思路

对于每个外层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于(top,left),右下角位于(bottom,right)

按照如下顺序遍历当前层的元素:

  1.从左到右,遍历最上层元素,依次为 (top,left) 到 (top,right)

  2.从上到下,遍历最右层元素,依次为(top+1,right) 到(bottom,right)。

  3.如果left<right 且 top<bottom,则从右到左遍历下侧元素依次为 (bottom,right−1) 到 (bottom,left+1),以及从下到上遍历左侧元素依次为(bottom,left)到(top+1,left)。

  情况3存在于长方形中

遍历完当前最外层的元素后,将 left 和top 分别增加 1,将 right 和 bottom 分别减少 1,从而进入下一层,直到结束。

实现

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return matrix       
        rows, columns = len(matrix), len(matrix[0])
        result = []
        left, right, top, bottom = 0, columns - 1, 0, rows - 1
        while left <= right and top <= bottom:
            for column in range(left, right + 1):
                result.append(matrix[top][column])
            for row in range(top + 1, bottom + 1):
                result.append(matrix[row][right])
            if left < right and top < bottom:
                for column in range(right - 1, left, -1):
                    result.append(matrix[bottom][column])
                for row in range(bottom, top, -1):
                    result.append(matrix[row][left])
            left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
        return result
原文地址:https://www.cnblogs.com/mgdzy/p/13434203.html