Traverse a Matrix in Spiral Order
Implement spiralOrder
Given a matrix, return every element visited in spiral order — starting at the top-left, sweeping right across the top row, down the right column, left across the bottom row, up the left column, then spiraling inward and repeating until every cell has been visited.
Tracking a visited grid works, but it wastes memory the traversal doesn't actually need: the boundary between "visited" and "unvisited" is always a clean rectangle shrinking inward, so four boundary pointers (top, bottom, left, right) are enough to know exactly which cells remain — no per-cell bookkeeping required.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[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]
Example 3:
Input: matrix = [[7]]
Output: [7]
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ rows, cols ≤ 10 - ●
-100 ≤ matrix[i][j] ≤ 100
matrix =
[[1,2,3], [4,5,6], [7,8,9]]