[Algorithm Problem 9 Spiral Matrix Problem]

Spiral Matrix 1: Source LeetCode54 Question

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)] is to prevent pop errors when the matrix is ​​empty, and short-circuit mechanism: when the matrix is ​​[], the statement after and will not be executed.

[::-1] rotate every time

The idea is as follows:

Spiral Matrix 2: Source LeetCode59 Question

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)
        

The idea is as follows:

 

where A*(n>0) is to deal with the case of n=0. If n=0, the return value is [], and if return A is returned [[0]] does not meet the requirements.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325259844&siteId=291194637