sagelearnai

Spiral Matrix II

Difficulty: Medium · Pattern: Matrix · LeetCode #59

Generate an n × n matrix filled with 1 to n² in spiral order.

Example

text
n = 3  →  [[1,2,3],[8,9,4],[7,6,5]]

Hints

  1. Reuse the Spiral Matrix boundaries, but write a counter instead of reading.
  2. Or simulate with a direction vector, turning right whenever the next cell is out of bounds or already filled.

Approach

Direction simulation: dirs = [(0,1),(1,0),(0,-1),(-1,0)]. Place k = 1..n². If the next cell is outside the grid or already non-zero, rotate the direction d = (d + 1) % 4. O(n²). This version generalizes neatly to any spiral-walk problem (Spiral Matrix III, IV).

Complexity

Time: O(n²). Space: O(1) besides the output.

Python solution
def generateMatrix(n):
    m = [[0] * n for _ in range(n)]
    dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    r = c = d = 0
    for k in range(1, n * n + 1):
        m[r][c] = k
        nr, nc = r + dirs[d][0], c + dirs[d][1]
        if not (0 <= nr < n and 0 <= nc < n and m[nr][nc] == 0):
            d = (d + 1) % 4
            nr, nc = r + dirs[d][0], c + dirs[d][1]
        r, c = nr, nc
    return m
JavaScript solution
function generateMatrix(n) {
  const m = Array.from({ length: n }, () => new Array(n).fill(0));
  let top = 0, bottom = n - 1, left = 0, right = n - 1, k = 1;
  while (k <= n * n) {
    for (let c = left; c <= right; c++) m[top][c] = k++;
    top++;
    for (let r = top; r <= bottom; r++) m[r][right] = k++;
    right--;
    for (let c = right; c >= left; c--) m[bottom][c] = k++;
    bottom--;
    for (let r = bottom; r >= top; r--) m[r][left] = k++;
    left++;
  }
  return m;
}