Spiral Matrix I

HardAcc. 68.2%
+50 XP 25

The Perimeter Collapse (Spiral)

Navigating a matrix in a spiral is a test of boundary logic. You must travel along the top row, then down the right side, across the bottom, and up the left—repeating the cycle while shrinking your "search perimeter" at every turn.

The Assignment

Your mission is to traverse the matrix in a clockwise spiral. Your function receives matrix.

  1. Define four boundaries: top, bottom, left, and right.
  2. While the boundaries have not crossed each other:
    • Move from left to right across the current top row.
    • Move from top to bottom down the current right column.
    • Move from right to left across the current bottom row (only if top <= bottom).
    • Move from bottom to top up the current left column (only if left <= right).
  3. Print every element you visit on a separate line.

01EXAMPLE 1

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

Explanation: Spiral path.

Constraints

  • Maintain boundary logic carefully.
ArraysMatrixAlgorithms
JavaScript
Loading...
1 Hidden

Input Arguments

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

Expected Output

1
2
3
6
9
8
7
4
5

Click RUN to test your solution