Spiral Matrix II
The key idea
Walk the grid in the spiral order itself, writing the next counter value into each visited cell. Either shrink four boundaries (top, bottom, left, right) after each edge, or step in a direction vector and turn clockwise whenever the next cell is out of bounds or already filled.
Problem
Given a positive integer n, generate an n x n matrix filled with the elements from 1 to n^2 in spiral order (clockwise).
The spiral starts in the top-left corner, moves right across the top row, then down the right column, then left across the bottom row, then up the left column, and continues winding inward until every cell from 1 to n^2 is filled. Return the completed matrix.
Constraints
1 <= n <= 20
Examples
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Input: n = 1
Output: [[1]]
Complexity
Time: O(n^2) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Matrix / Grid problems
- Game of LifeMEDIUM
- Island PerimeterEASY
- Rotate ImageMEDIUM
- Search a 2D Matrix IIMEDIUM
- Set Matrix ZeroesMEDIUM
- Spiral MatrixMEDIUM
- Transpose MatrixEASY