Spiral Matrix II

Given a positive integer n, generate an n x n matrix filled with the integers from 1 to n^2 in spiral order.

Return the completed matrix as a 2D integer array.

Example 1
Inputn = 3
Output[[1,2,3],[8,9,4],[7,6,5]]
The numbers from 1 to 9 are placed clockwise in spiral order in a 3 x 3 matrix.
Example 2
Inputn = 1
Output[[1]]
A 1 x 1 matrix contains only the number 1.

Constraints

  • 1 <= n <= 20

Asked at 9 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate