Fill an n x n Grid in Spiral Order
Problem statement
Given a positive integer n, build an n x n grid holding the numbers 1 to n * n in a clockwise spiral.
Start at the top-left cell with 1 and move right. Each time the next cell would be outside the grid or already filled, turn clockwise (right, then down, then left, then up, and so on). Return the grid as a list of rows.
Function
spiralFill(n: int) → int[][]Examples
Example 1
n = 2return = [[1,2],[4,3]]1 and 2 go along the top row, 3 goes down the right side, and 4 goes left along the bottom row.
Example 2
n = 4return = [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]The outer ring takes 1 to 12: 1 to 4 across the top, 5 to 7 down the right side, 8 to 10 back along the bottom, 11 and 12 up the left side. The inner 2 by 2 block then takes 13 to 16 in the same clockwise order, starting at row 1, column 1.
Example 3
n = 5return = [[1,2,3,4,5],[16,17,18,19,6],[15,24,25,20,7],[14,23,22,21,8],[13,12,11,10,9]]The outer ring takes 1 to 16, the next ring takes 17 to 24, and the single center cell gets the last number, 25.
Constraints
1 <= n <= 40