← All problems

Spiral Matrix

medium

Given an m x n matrix, return all of its elements in spiral order — right across the top, down the right edge, left across the bottom, up the left edge, then shrink inward and repeat.

Track four shrinking boundaries (top, bottom, left, right) and walk each edge in turn, moving the corresponding boundary inward after each edge.

Example

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