Leetcode练习(Python):数组类:第54题:给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

题目:
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
思路:
使用两个指针,然后控制好边界就可以了。
程序:
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

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12737090.html