54. Spiral Matrix

https://leetcode.com/problems/spiral-matrix/

solution

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []

        start_col = 0
        start_row = 0
        n_col = len(matrix[0]) - 1
        n_row = len(matrix) - 1

        res = []  # [[0 for _ in range(n_row)] for _ in range(n_col)]

        while start_col <= n_col and start_row <= n_row:
            for i in range(start_col, n_col+1):
                res.append(matrix[start_row][i])
            start_row += 1

            for i in range(start_row, n_row+1):
                res.append(matrix[i][n_col])
            n_col -= 1

            if start_row <= n_row:
                for i in range(n_col, start_col - 1, -1):
                    res.append(matrix[n_row][i])
                n_row -= 1

            if start_col <= n_col:
                for i in range(n_row, start_row - 1, -1):
                    res.append(matrix[i][start_col])
                start_col += 1
        return res

时间复杂度:O() 空间复杂度:O()

Last updated