Spiral Matrix II
Medium · Matrix · Array · Matrix · Simulation
Problem
Given a positive integer n, build an n x n matrix filled with the numbers 1 to n^2 in spiral order: start in the top-left corner going right, turn clockwise whenever you would leave the grid or hit a filled cell, and continue until all cells are filled.
Examples
Input: n = 1 Output: [[1]]
A single cell holds 1.
Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]
The border holds 1 to 8 clockwise and 9 lands in the center.
Input: n = 4 Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
The outer ring takes 1 to 12, the inner ring 13 to 16.
Constraints
- 1 <= n <= 20
Approaches
- Walk and turn when blocked — time O(n²), space O(1) beyond the output
Follow-up
Can you find the number at a given cell (r, c) without building the matrix, even for n up to 10^9? The cell lies on ring d = min(r, c, n-1-r, n-1-c); the rings outside it hold n² - (n-2d)² numbers, and the position along its own ring follows from which side it is on.
Related problems
Start free on Cariara · Coding problems · System design studio