Matrix Spiral Traversal

Languages

Given a matrix of size m x n, write a function to return the elements of the matrix arranged in a spiral order.

Input

  • matrix: number[][]: A 2D array matrix of size m x n

Examples

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Explanation: Starting from the top-left corner, move right across the first row, then go down across the last column, then move left along the bottom row, and travel up in the first column. Continue this pattern, spiraling inward, until all the elements have been traversed.
Input: matrix = [[7,7,0,7],[4,3,7,2],[9,8,6,0],[6,1,3,6]]
Output: [7,7,0,7,2,0,6,3,1,6,9,4,3,7,6,8]
Explanation: Starting from the top-left corner, move right across the first row, then go down in the last column, move left along the bottom row, and travel up in the first column. Continue this pattern, spiraling inward, until all the elements have been traversed.
Input: matrix = [[1,2],[3,4]]
Output: [1,2,4,3]
Explanation: Starting from the top-left corner, move right across the first row, then go down in the last column, and finally move left across the bottom row.

Constraints

  • 1 <= m, n <= 100
  • -1,000 <= matrix[row][col] <= 1,000
The fastest way to learn Front End – by building actual projects

Want to grow in your front end skills? Learn them the right way — build apps step-by-step while referencing best practices from Senior engineers.

Get 30% off now with BETA30 →

The fastest way to learn Front End – by building actual projects

Want to grow in your front end skills? Learn them the right way — build apps step-by-step while referencing best practices from Senior engineers.

Get 30% off now with BETA30 →