Algorithm -- LC Matrix_Spiral Matrix

1. 054 Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

1.1. Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

1.2. Example 2:

Input: matrix = [[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]

1.3. Constraints:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

2 Process

2.1 analysis

  • Scan matrix first row, append to temp = []
  • Remove maxtrix first row
  • Rotate the new matrix by 90 degrees (anticlockwise) by 【LC 048】
  • Repeat above steps

2.2 Code for Rotate Matrix

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything,
        modify matrix in-place instead.
        """
        temp = zip(*matrix[::-1])
        matrix[:] = list(temp)

same result

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything,
        modify matrix in-place instead.
        """
        matrix_new = []
        for i in range(len(matrix)):
            temp = []
            for j in range(-1, -len(matrix)-1, -1):
                temp.append(matrix[j][i])
            matrix_new.append(temp)
        matrix[:] = matrix_new
Matrix:
 [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
result:
 [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

2.3 Code for Spiral Matrix

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        nums = []
        mrow = len(matrix)
        mcol = len(matrix[0])
        while mrow:
            for i in range(mcol):
                nums.append(matrix[0][i])
            if mrow == 1:
                break
            matrix[:] = matrix[1:]
            matrix[:] = list(zip(*matrix))[::-1]
            mrow = len(matrix)
            mcol = len(matrix[0])
        return nums
Matrix:
 [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
result:
 [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]

おすすめ

転載: blog.csdn.net/minovophy/article/details/121391816