LeetCode

54. 螺旋矩阵

2021-03-15  本文已影响0人  MarcQAQ

给你一个 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])
上一篇下一篇

猜你喜欢

热点阅读