Spiral Matrix in Python

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

        # Initialize the boundaries of the matrix
        top, bottom = 0, len(matrix)
        left, right = 0, len(matrix[0])
        result = []

        while left < right and top < bottom:
            # Traverse from left to right
            for i in range(left, right):
                result.append(matrix[top][i])
            top += 1  # Move the top boundary down

            # Traverse from top to bottom
            for i in range(top, bottom):
                result.append(matrix[i][right - 1])
            right -= 1  # Move the right boundary left

            if not (left < right and top < bottom):
                break  # Check if there are still layers to process

            # Traverse from right to left
            for i in range(right - 1, left - 1, -1):
                result.append(matrix[bottom - 1][i])
            bottom -= 1  # Move the bottom boundary up

            # Traverse from bottom to top
            for i in range(bottom - 1, top - 1, -1):
                result.append(matrix[i][left])
            left += 1  # Move the left boundary right

        return result

PrevNext