spiral-matrix-ii.sh — zsh
arraysmatrixsimulation

Given an integer n, generate an n x n matrix filled with the numbers 1 through n^2 in clockwise spiral order.

Start at the top-left corner, move right first, and keep turning clockwise whenever you would leave the current unfilled region.

Input / output

  • Input: n: int
  • Output: int[][]

Examples

  1. n = 1 returns [[1]].
  2. n = 3 returns [[1,2,3],[8,9,4],[7,6,5]].
  3. n = 4 returns [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]].

Constraints

  • 1 <= n <= 20

Follow-up Can you describe the loop invariant for the four shrinking boundaries, and why odd-sized matrices do not need a special center-case branch?

Examples
Example 1
Input: n = 1
Output: [[1]]
Example 2
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 3
Input: n = 4
Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.