Spiral Matrix

Medium~20 min

Given an m x n matrix, return all elements of the matrix in spiral order (clockwise, starting from the top-left corner).

Spiral order means: traverse the top row left to right, then the right column top to bottom, then the bottom row right to left, then the left column bottom to top, and repeat inward.

Examples

Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Explanation: Spiral order: top row [1,2,3], right column [6,9], bottom row [8,7], left column [4], center [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]
Explanation: Top row [1,2,3,4], right column [8,12], bottom row [11,10,9], left column [5], remaining row [6,7].
Example 3
Input: matrix = [[1]]
Output: [1]
Explanation: A single element matrix returns just that element.

Constraints

  • 1 <= m, n <= 100
  • -100 <= matrix[i][j] <= 100
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run