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.
Example 3
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]clockwise = truereturn = [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]Exercises two complete clockwise rings and the inner two-by-two boundary.
Constraints
matrixhas at least one row and one column.- Every row has the same number of columns.
- Every matrix value is a signed integer.