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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM