Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. Tags: Matrix

Try It!

Discussion

Video

Solution

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        row_lo = 0
        row_hi = len(matrix) - 1
        col_lo = 0
        col_hi = len(matrix[0]) - 1

        while row_lo <= row_hi and col_lo <= col_hi:
            for c in range(col_lo, col_hi + 1):
                res.append(matrix[row_lo][c])
            row_lo += 1

            for r in range(row_lo, row_hi + 1):
                res.append(matrix[r][col_hi])
            col_hi -= 1

            if row_lo <= row_hi:
                for c in range(col_hi, col_lo - 1, -1):
                    res.append(matrix[row_hi][c])
            row_hi -= 1

            if col_lo <= col_hi:
                for r in range(row_hi, row_lo - 1, -1):
                    res.append(matrix[r][col_lo])
            col_lo += 1
        
        return res