Spiral Matrix

Return all elements of a matrix in spiral order, starting at the top-left and moving clockwise.

A way to picture it

Peel an onion one ring at a time. Walk along the top, down the right, back along the bottom and up the left — then step inside to the next ring and do it again, until there's nothing left.

How to approach it

Keep four boundaries: top, bottom, left, right. Walk one side, then shrink that boundary. Stop when the boundaries cross.

Example

Input: {"matrix":[[1,2,3],[4,5,6],[7,8,9]]}. Output: [1,2,3,6,9,8,7,4,5].

Complexity: O(m · n) time and O(1) extra space. Every cell is visited exactly once.

This page includes an animated walkthrough, Java and Python solutions, and a question to check your understanding.