Spiral Matrix
Given a 2D matrix of integers, return all elements of the matrix in spiral order. Starting from the top-left corner of the matrix, you should proceed in a spiral pattern until all elements have been visited.
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Explanation. The numbers are returned in the outermost elements first, rounding the edge of the matrix, and then progressing inward in a spiral manner.
[ [ 1, 2 ], [ 3, 4 ] ]
Explanation. Starting at the top-left corner and moving right, then down, then left to cover the matrix in a spiral manner.
[ [ 1 ] ]
Explanation. The matrix contains only one element.
Follow-up: Can you solve this problem in-place, using O(1) additional space?
The given matrix will not be empty and will have a rectangular shape, meaning all rows are of the same length.
- Views
- 3