Matrix Spiral Copy
Given a 2D matrix of integers, write a function that returns an array of its elements in spiral order.
For example, given the input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
The function should return [1,2,3,6,9,8,7,4,5].
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Explanation. Starting from the top-left corner, the function first traverses the top row from left to right. It then traverses the last column top to bottom, followed by the bottom row right to left, and finally the first column bottom to top.
[ [ 1, 2 ], [ 3, 4 ] ]
Explanation. The traversal starts at the top-left, moving right across the top row, then down the right column, then left across the bottom row.
[ [ 1 ] ]
Explanation. With a single element, the spiral is simply the element itself.
Follow-up: How would your solution change if the matrix could also include negative integers or zeros?
The matrix will have at least 1x1 dimensions and will contain only integers.
- Views
- 3