\

Spiral Matrix

Difficulty: N/A | Solved: October 1, 2024

Problem

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Brainstorming

The core idea is to simulate the spiral path. We maintain boundaries (top, bottom, left, right) and shrink them as we traverse each side.

  1. Initialize boundaries:
    • top = 0
    • bottom = m - 1
    • left = 0
    • right = n - 1
  2. Loop while boundaries are valid:
    • Move Right: Traverse from left to right along the top row. Then increment top.
    • Move Down: Traverse from top to bottom along the right column. Then decrement right.
    • Move Left (if top <= bottom): Traverse from right to left along the bottom row. Then decrement bottom.
    • Move Up (if left <= right): Traverse from bottom to top along the left column. Then increment left.

Code

def spiralOrder(matrix):
    if not matrix:
        return []
    
    m, n = len(matrix), len(matrix[0])
    top, bottom = 0, m - 1
    left, right = 0, n - 1
    result = []
    
    while top <= bottom and left <= right:
        # Move Right
        for i in range(left, right + 1):
            result.append(matrix[top][i])
        top += 1
        
        # Move Down
        for i in range(top, bottom + 1):
            result.append(matrix[i][right])
        right -= 1
        
        # Move Left
        if top <= bottom:
            for i in range(right, left - 1, -1):
                result.append(matrix[bottom][i])
            bottom -= 1
            
        # Move Up
        if left <= right:
            for i in range(bottom, top - 1, -1):
                result.append(matrix[i][left])
            left += 1
            
    return result