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

Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:[1,2,3,6,9,8,7,4,5]
Explanation:

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].

Input:matrix = [[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:

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].

Input:matrix = [[7,3],[9,-2],[5,1]]
Output:[7,3,-2,1,5,9]
Explanation:

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

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!