问题描述

给定一个包含 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]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


解题思路

逐圈打印


Python 实现

class Solution(object):
    def output_a_circle(self, matrix, left_x, left_y, right_x, right_y):
        result = []
        if left_x > right_x or left_y > right_y:
            raise RuntimeError("invalid input")
        for ind in range(left_y, right_y + 1):
            result.append(matrix[left_x][ind])
        for ind in range(left_x + 1, right_x):
            result.append(matrix[ind][right_y])
        if right_x > left_x:
            for ind in range(right_y, left_y - 1, -1):
                result.append(matrix[right_x][ind])
        if right_y > left_y:
            for ind in range(right_x - 1, left_x, -1):
                result.append(matrix[ind][left_y])
        return result

    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if not matrix:
            return []

        result = []
        m = len(matrix)
        n = len(matrix[0])
        left_x = 0
        left_y = 0
        right_x = m - 1
        right_y = n - 1

        while left_x <= right_x and left_y <= right_y:
            result.extend(
                self.output_a_circle(
                    matrix, left_x, left_y, right_x, right_y))
            left_x = left_x + 1
            left_y = left_y + 1
            right_x = right_x - 1
            right_y = right_y - 1
        return result