Problem · Array
Generate Spiral Matrix
Learn this problemProblem statement
Given a positive integer n, generate an n by n matrix filled with the integers from 1 through n * n in clockwise spiral order.
Place 1 in the top-left cell and begin by moving to the right. Turn clockwise whenever the next cell would leave the matrix or revisit an already filled cell.
Function
generateMatrix(n: int) → int[][]Examples
Example 1
n = 3return = [[1,2,3],[8,9,4],[7,6,5]]The values follow the outer clockwise ring before filling the center with 9.
Example 2
n = 1return = [[1]]A one-cell matrix contains only 1.
Example 3
n = 4return = [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]Each completed boundary shrinks inward until all 16 values are written.
Constraints
1 <= n <= 100.- The result contains each integer from
1throughn * nexactly once.