Problems

Spiral Matrix

medium
medium
arrays
matrix

Generate an n x n matrix containing the integers from 1 through in clockwise spiral order, starting at the top-left corner.

Input / output

  • Input: n: integer
  • Output: integer[][]

Examples

  1. n = 3 returns [[1,2,3],[8,9,4],[7,6,5]].
  2. n = 1 returns [[1]].

Constraints

  • 1 <= n <= 50

Follow-up Can you describe the loop invariant for the four moving boundaries and avoid special-case center logic?

Examples

Example 1

Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2

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

Example 3

Input: n = 1
Output: [[1]]
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.