Spiral Order Print

Medium~20 min

Given an m x n matrix, return all elements 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.

For example, given:

1  2  3
4  5  6
7  8  9

The spiral order is [1, 2, 3, 6, 9, 8, 7, 4, 5].

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: Top row → right column → bottom row reversed → left column reversed → center.
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: Spiral through the 3x4 matrix.
Example 3
Input: matrix = [[1]]
Output: [1]
Explanation: Single element.

Constraints

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

Run your code to see results

Use Cmd+Enter to run