10. Spiral Matrix
Visit the outer boundary clockwise, beginning at the top-left corner and moving right. Continue with the next inner boundary until every cell has been visited exactly once.
Return values rather than coordinates. Repeated values from different cells must all appear, and the matrix must remain unchanged.
Example 1
Input
[[1,2,3],[4,5,6],[7,8,9]]
Output
[1,2,3,6,9,8,7,4,5]
Explanation: Visit the outer perimeter clockwise, then the remaining center.
Example 2
Input
[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output
[1,2,3,4,8,12,11,10,9,5,6,7]
Explanation: After removing the outer ring, the final remaining row is read once.
Constraints
0 <= matrix.length <= 1000 <= matrix[r].length <= 100-231 <= matrix[r][c] <= 231 - 1- The matrix is rectangular and all rows are non-null.
Hints
Hint 1
What shape remains after removing one complete outer perimeter?
Hint 2
Represent the unvisited rectangle by four bounds.
Hint 3
Consume each edge once, shrink immediately, and guard a collapsed final row or column.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Peel the outer ring
[[1,2,3],[4,5,6],[7,8,9]]
[1,2,3,6,9,8,7,4,5]