Traverse a 2D matrix in clockwise spiral order, starting from the top-left corner.
Write a function `spiral_order(matrix)` that takes a 2D list of integers `matrix` and returns a list of all the elements in clockwise spiral order, starting from the top-left corner and moving right, then down, then left, then up, repeating until every element has been visited.
- The matrix is a rectangular list of lists; each inner list has the same length.
- If the matrix is empty (`[]`), return an empty list.
- If the matrix is a single row or single column, just return that row or column in order.
- You may assume the matrix contains only integers.
**Function signature:**
```python
def spiral_order(matrix: list[list[int]]) -> list[int]:
```
Constraints
- 0 <= number of rows <= 100
- 0 <= number of columns <= 100
- -1000 <= matrix[i][j] <= 1000
- Expected time complexity O(n*m), space complexity O(n*m) for the output.
Example
```python
>>> spiral_order([[1,2,3],[4,5,6],[7,8,9]])
[1,2,3,6,9,8,7,4,5]
>>> spiral_order([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
[1,2,3,4,8,12,11,10,9,5,6,7]
>>> spiral_order([[1],[2],[3]])
[1,2,3]
>>> spiral_order([])
[]
```
25 points
~25 min