Problem · Matrix
Spiral Matrix Traversal
Learn this problemProblem statement
Given a non-empty rectangular integer matrix matrix and a boolean clockwise, return all values in spiral order.
- When
clockwiseistrue, start at the top-left cell and initially move right. - When
clockwiseisfalse, start at the top-left cell and initially move down. - Visit every cell exactly once.
Function
spiralOrder(matrix: int[][], clockwise: boolean) → int[]Examples
Example 1
matrix = [[1,2,3],[4,5,6],[7,8,9]]clockwise = truereturn = [1,2,3,6,9,8,7,4,5]The traversal follows the top row, right edge, bottom row, left edge, and then the center.
Example 2
matrix = [[1,2,3,4,5]]clockwise = falsereturn = [1,2,3,4,5]A single row has only one possible visit order from the top-left cell.
Constraints
matrixhas at least one row and one column.- Every row has the same number of columns.
- Every matrix value is a signed integer.