Given a positive integer n, generate an n x n matrix filled with the integers from 1 to n * n in spiral order.
Function Signature
def generate_matrix(n: int) -> list[list[int]]:
Rules
-
The spiral is clockwise and starts with
1
in the top-left corner. It moves right along the top row, then down the right column, left along the bottom row, and up the left column, continuing inward.
-
Each value is one greater than the value placed before it, so every integer from
1
to
n * n
appears exactly once.
-
Return the matrix as a list of
n
rows, each a list of
n
integers.
Constraints
Examples
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
The values 1 to 3 fill the top row, 4 and 5 go down the right column, 6 and 7 run back along the bottom row, 8 goes up the left column, and 9 lands in the center.
Input: n = 1
Output: [[1]]
A 1x1 matrix contains only the value 1.
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 clockwise from the top-left corner. The inner 2x2 block then takes 13 to 16, again starting at its own top-left cell.