Spiral Matrix Traversal

Matrix Traversal Algorithm

Problem: Spiral Matrix Traversal

Write a function that takes a 2D matrix (a list of lists) of integers and returns the elements of the matrix in spiral order (clockwise).

For example, given the following matrix:

[
  [1,  2,  3,  4],
  [5,  6,  7,  8],
  [9, 10, 11, 12]
]

Your function should return: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7].

Additional Context

On February 25, we celebrate various historical events around the world. Today’s problem invites you to navigate a matrix as if exploring a historical map—traverse every element in a smooth, spiraling journey.

Function Signature

Your solution should implement a function that accepts a matrix and returns an array (or list) of integers in spiral order.

  • Input: A 2D list (matrix) of integers.
  • Output: A list of integers representing the matrix elements in spiral order.