JavaScriptMediumMatrices20 min

Traverse a matrix in spiral order

Return matrix values in clockwise spiral order, starting at the top-left corner. An empty matrix returns []. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess shrink four boundaries after traversing each outer edge.

Input

A JSON rectangular matrix of integers; [] is allowed.

Output

Print one compact JSON value: an array of integers.

Constraints

For nonempty matrices, 1 <= rows, columns <= 100; values between -1000000 and 1000000.

Example

Input

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

Output

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

Example 2 input

[[0,-1,2]]

Output

[0,-1,2]

Boundary case: Guard the bottom and left traversals to avoid revisiting a single row or column

Public test cases (2)

  • Input

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

    Expected output

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

    [[1,2,3],[4,5,6]]

    Expected output

    [1,2,3,6,5,4]
Hints (2)
  1. Process top row, right column, bottom row, then left column
  2. Guard the bottom and left traversals to avoid revisiting a single row or column

Target complexity: time O(rows * columns) · space O(rows * columns)

Your solution

Checking runner availability…

Reference solution

Sign in for solution
All JavaScript programs