Leetcode.54.螺旋矩阵

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

1 思路:

  • 从[i,i]坐标开始按照顺时针输出每一层的数字
  • 一共循环的次数$ n = \left \lceil min(row,col)/2 \right \rceil $
    对于一维矩阵直接输出,
    思路比较简单就是索引比较麻烦。运行时间比较长。时间复杂度O(n)。n是col*row.
import numpy as np
class Solution:
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        def toouter(matrix,indexs):
            n,m = indexs
            outer = []
            p,q = len(matrix),len(matrix[0])
            for i in range(m,q-m):
                outer.append(matrix[n][i])
           
            for i in range(n+1,p - n):
                outer.append(matrix[i][q-m-1])
            if p-n-1 > n:
                for i in range(q-m-2,m-1,-1):
                    outer.append(matrix[p-n-1][i])
            if q-m-1 > m: 
                for i in range(p - n -2,n,-1):
                    outer.append(matrix[i][m])
            return outer
        if len(np.array(matrix).shape) == 2:
            size = len(matrix),len(matrix[0])
            minnum =  size[0] if size[0] < size[1] else size[1]
            indexnum = int(np.ceil(minnum / 2))

            outarray = []
            for i in range(indexnum):
                outarray.extend(toouter(matrix,(i,i)))
            return outarray
        else:
            return matrix

猜你喜欢

转载自blog.csdn.net/qq_20966795/article/details/84963177