67. Spiral Matrix Traversal

MediumArrayArray

Given an m x n matrix, return all elements of the matrix in spiral order (clockwise, starting from the top-left).

Input: A 2D integer array matrix of size m x n.

Output: List of integers in spiral traversal order.

Examples

Example 1
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Explanation: Top row: 1,2,3. Right col: 6,9. Bottom row (reverse): 8,7. Left col (up): 4. Center: 5.
Example 2
Input: [[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: Top: 1,2,3,4. Right: 8,12. Bottom (rev): 11,10,9. Left: 5. Middle row: 6,7.
Example 3
Input: [[1]]
Output: [1]
Explanation: Single element.

Constraints

Asked by

OracleAppleMicrosoftAmazonBloombergAdobe
Solve this problem in the editor →