Spiral Matrix Display

Matrix Traversal Spiral Algorithm

Spiral Matrix Display

Guy Fawkes Night is nearly here! Imagine a historical fireworks display arranged in a matrix. Each cell in the matrix represents the intensity of fireworks at that spot. Your task is to traverse the matrix in a spiral order (clockwise starting from the top-left corner) and return an array containing the intensities in the order they were visited.

Problem Statement

Write a function that takes a 2D matrix (which may be rectangular) of integers and returns an array of integers representing the spiral traversal from the outermost elements to the innermost. The traversal should start from the top-left element and proceed in a clockwise spiral.

Example

For the matrix:

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

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

Function Signature

Your function should have the following signature (or similar in your chosen language):

spiralTraverse(matrix: number[][]) => number[]

Constraints

  • The matrix will have at least 1 row and 1 column.
  • You may assume all inputs are valid integers.

Good luck and enjoy lighting up the night with your code!