【算法题9 螺旋矩阵问题】
螺旋矩阵1:来源LeetCode54题
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
class Solution: def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])
matrix and [*matrix.pop(0)]是为了防止matrix为空时进行pop出错,and短路机制:matrix为[]时不再执行and后的语句。
[::-1]每次都要进行旋转
思路如下路:
螺旋矩阵2:来源LeetCode59题
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution: def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ A=[[n*n]] while A[0][0]>1: A=[list(range(A[0][0]-len(A),A[0][0]))]+list(zip(*A[::-1])) return A*(n>0)
思路如下:
其中的A*(n>0)是为了处理n=0的情况。若n=0,返回值为[],若return A则返回[[0]]不符合要求。