Practice

Spiral Matrix

Module 15 · Matrix / 2D Traversal

Problem

Given an m × n matrix, return all its elements in spiral order — starting at the top-left, walking the outer ring clockwise (right, down, left, up), then spiralling inward ring by ring until every element is collected. (LeetCode 54.)

Examples

Example 1

Inputmatrix = [[1,2,3],[4,5,6],[7,8,9]]Output[1,2,3,6,9,8,7,4,5]

Example 2

Inputmatrix = [[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]

Constraints

1 ≤ m, n ≤ 10, values in ±100. Note the grid is m × nnot necessarily square — which is exactly where the subtle bug in this problem lives.

Attempt it first

This is the direct application of the concept lesson's spiral traversal (Traversal Orders). The mechanics — four moving boundaries fencing the un-visited rectangle, each edge-walk shrinking one boundary inward — are already derived there. Your job is to reproduce it correctly on a non-square grid, which means getting the two inner guards right. Before revealing anything, write the four edge-walks and ask yourself: after I've walked the top row and the right column, what goes wrong on a grid that has only one row, or only one column, left?