Description
Given an m x n matrix, return all elements of the matrix in spiral order. Start from the top-left corner and move right, down, left, up, spiraling inward.
Examples
matrix = [[1,2,3],[4,5,6],[7,8,9]][1,2,3,6,9,8,7,4,5]Starting at (0,0): go right collecting [1,2,3], then down at column 2 collecting [6,9], then left at row 2 collecting [8,7], then up at column 0 collecting [4], finally right at row 1 collecting [5]. The complete spiral path is [1,2,3,6,9,8,7,4,5].
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]][1,2,3,4,8,12,11,10,9,5,6,7]Starting at (0,0): go right [1,2,3,4], down [8,12], left [11,10,9], up [5], then inner spiral right [6,7]. Complete path: [1,2,3,4,8,12,11,10,9,5,6,7].
matrix = [[7,3],[9,-2],[5,1]][7,3,-2,1,5,9]For this 3x2 matrix [[7,3],[9,-2],[5,1]]: start at (0,0), go right collecting [7,3]. At column 1, go down collecting [-2,1]. At row 2, go left collecting [5]. At column 0, go up collecting [9]. Complete path: [7,3,-2,1,5,9]. The negative value -2 is included naturally in the traversal order.
Constraints
- •
m == matrix.length - •
n == matrix[i].length - •
1 ≤ m, n ≤ 10 - •
-100 ≤ matrix[i][j] ≤ 100