Spiral Matrix
MediumMath & Geometry · Apple
You are given an m x n integer matrix. Return all of its elements in clockwise spiral order, as a single list.
Spiral order starts at the top-left cell, moves right along the top row, then down the right column, then left along the bottom row, then up the left column, and then repeats the same pattern on the remaining inner rectangle until every cell has been visited exactly once.
Example 1
- Input:
- matrix = [[3,1,2],[6,4,5],[9,7,8]]
- Output:
- [3,1,2,5,8,7,9,6,4]
- Explanation
- Across the top row (3, 1, 2), down the right column (5, 8), back along the bottom (7, 9), up the left column (6), and finally the centre (4).
Example 2
- Input:
- matrix = [[2,4],[6,8],[10,12]]
- Output:
- [2,4,8,12,10,6]
- Explanation
- Top row 2, 4; down the right column 8, 12; back along the bottom 10; then up the left column to 6. Every value appears exactly once.
Example 3
- Input:
- matrix = [[5,-1,3]]
- Output:
- [5,-1,3]
- Explanation
- With only one row, the spiral is just that row read left to right.
Constraints
m == matrix.length,n == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100