美文网首页LeetCode
54. 螺旋矩阵

54. 螺旋矩阵

作者: MarcQAQ | 来源:发表于2021-03-15 09:04 被阅读0次

    给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
    输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
    输出:[1,2,3,6,9,8,7,4,5]

    观察给出的例子,根据上,右,下,左的顺序依次输出最外面的一层,然后再利用递归,打印第二层,直到矩阵的最内层。


    image.png
    class Solution:
        def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
            result = list()
            rows = len(matrix)
            cols = len(matrix[0])
            self.spiralOrderOuterLayer(matrix, (0, 0), (rows - 1, cols - 1), result)
    
            return result
    
        def spiralOrderOuterLayer(self, matrix, top_left, bottom_right, current_sequence):
            top_left_row, top_left_col = top_left
            bottom_right_row, bottom_right_col = bottom_right
            
            if top_left_row < bottom_right_row and top_left_col < bottom_right_col:
                # print the outer layer in the orders of top, right, bottom, left
                for col in range(top_left_col, bottom_right_col):
                    current_sequence.append(matrix[top_left_row][col])
                for row in range(top_left_row, bottom_right_row):
                    current_sequence.append(matrix[row][bottom_right_col])
                for col in range(bottom_right_col, top_left_col, -1):
                    current_sequence.append(matrix[bottom_right_row][col])
                for row in range(bottom_right_row, top_left_row, -1):
                    current_sequence.append(matrix[row][top_left_col])
                # recursively print for the rest matrix
                self.spiralOrderOuterLayer(
                    matrix,
                    (top_left_row + 1, top_left_col + 1),
                    (bottom_right_row - 1, bottom_right_col - 1),
                    current_sequence
                )
            elif top_left_col == bottom_right_col:
                # if the matrix is just one column
                for row in range(top_left_row, bottom_right_row + 1):
                    current_sequence.append(matrix[row][top_left_col])
            elif top_left_row == bottom_right_row:
                # if the matrix is just one row
                for col in range(top_left_col, bottom_right_col + 1):
                    current_sequence.append(matrix[top_left_row][col])
    

    相关文章

      网友评论

        本文标题:54. 螺旋矩阵

        本文链接:https://www.haomeiwen.com/subject/uiihcltx.html