Spiral Matrix
Given an m x n matrix, return its elements in spiral order.
Examples
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Input: [[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]
Hints
Use a direction vector (e.g., right, down, left, up) to control traversal order and a visited matrix to track processed cells.
Instead of a visited matrix, dynamically adjust the boundaries (top, bottom, left, right) after completing each spiral layer to avoid revisiting cells.
Implement boundary checks to handle non-rectangular matrices (e.g., empty rows or columns) by validating indices before traversal in each direction.
Related Problems
Spiral Matrix
Given an m x n matrix, return its elements in spiral order.