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.
- Define four boundaries:
top,bottom,left, andright. - While the boundaries have not crossed each other:
- Move from left to right across the current
toprow. - Move from top to bottom down the current
rightcolumn. - Move from right to left across the current
bottomrow (only if top <= bottom). - Move from bottom to top up the current
leftcolumn (only if left <= right).
- Move from left to right across the current
- Print every element you visit on a separate line.
01EXAMPLE 1
Input
[[1,2,3],[4,5,6],[7,8,9]]Output
1
2
3
6
9
8
7
4
5Explanation: Spiral path.
Constraints
- Maintain boundary logic carefully.
ArraysMatrixAlgorithms
JavaScriptSystem handles I/O — write your function only
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