Leetcode exercise (Python): Array class: Question 54: Given a matrix with mxn elements (m rows, n columns), return all the elements in the matrix in a clockwise spiral order.

topic:
Given a matrix of mxn elements (m rows, n columns), return all the elements in the matrix in a clockwise spiral order.
Ideas:
Use two pointers and control the boundary.
program:
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        row = len(matrix)
        if row <= 0:
            return []
        column = len(matrix[0])
        result = []

        row_begin = 0
        row_end = row - 1
        column_begin = 0
        column_end = column - 1

        while row_begin <= row_end and column_begin <= column_end:
            for index1 in range(column_begin, column_end + 1):
                result.append(matrix[row_begin][index1])
            row_begin += 1
            
            for index2 in range(row_begin, row_end + 1):
                result.append(matrix[index2][column_end])
            column_end -= 1

            for index1 in range(column_end, column_begin - 1, -1):
                if row_end >= row_begin:
                    result.append(matrix[row_end][index1])
            row_end -= 1

            for index2 in range(row_end, row_begin - 1, -1):
                if column_end >= column_begin:
                    result.append(matrix[index2][column_begin])
            column_begin += 1
        
        return result

Guess you like

Origin www.cnblogs.com/zhuozige/p/12737090.html