LC 54 — Problem

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

Input: matrix = 123,456,789
Output: 123698745
Input: matrix = 1234,5678,9101112
Output: 123481211109567

Constraints: m = matrix.length, n = matrix[i].length · 1 ≤ m, n ≤ 10

Spiral traversal shows up in image processing (reading pixels in scan-line spirals for compression), cache-friendly matrix access patterns, and matrix serialization for network transport. The task sounds mechanical: start at the top-left corner, walk right along the top row, then down the right column, then left across the bottom, then up the left side — peeling one ring at a time until every cell is visited.

The naive approach uses a boolean visited[m][n] matrix and a direction vector. Walk forward; when you hit a wall or a visited cell, turn clockwise. It works, but it wastes O(m*n) extra space for that visited matrix — a full copy of the grid just to remember where you have been.

Can we do better? Try tracing the spiral on a 4x4 matrix by hand. At each corner, you will have to choose which direction to go next. Pay attention to what makes the choice obvious — and what makes it confusing.

FIG. 1 — TRACE THE SPIRAL — CHOOSE DIRECTIONS AT EACH TURN

Straight segments auto-advance. At each corner, you choose the direction.