Description

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n² in spiral order.

Examples

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

Numbers 1-9 filled in spiral order.

Input:n = 1
Output:[[1]]
Explanation:

Edge case with minimal input.

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

For a 4x4 matrix, filling numbers 1-16 in spiral order: first row (1-4) left to right, right column (5-7) top to bottom, bottom row (8-10) right to left, left column (11-12) bottom to top, then continue the spiral inward with the remaining inner 2x2 matrix.

Constraints

  • 1 ≤ n ≤ 20

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!