Spiral Matrix Traversal

Matrix Traversal Spiral Algorithm

Problem Description

Given a 2D matrix of integers, write a function that returns all elements of the matrix in spiral order. The traversal starts from the top-left corner, moves right, then down, left, and up, repeating the process until all elements have been visited.

For example, given the following matrix:

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

The spiral order traversal would be: [1, 2, 3, 6, 9, 8, 7, 4, 5].

Note: Today, on March 9, we also remember historical milestones in computing that have paved the way for modern algorithms. Let that inspire you to think creatively about problem solving!

Function Signature

Implement the function with the following signature:

  • Input: A 2D matrix (list of lists or equivalent) containing integers.
  • Output: A list/array of integers representing the spiral order traversal.

Starter Code Examples

Below are starter code snippets in various languages to help you get started.