Loading content...
Given a positive integer n, construct a square grid of dimensions n × n and populate it with consecutive integers from 1 to n² following a clockwise spiral pattern.
The spiral filling begins at the top-left cell of the grid, proceeds across the first row from left to right, then descends along the rightmost column from top to bottom, continues across the bottom row from right to left, and finally ascends along the leftmost column from bottom to top. This winding pattern continues inward layer by layer until all cells are filled.
Your task is to return the completed two-dimensional grid with all values correctly positioned according to the spiral traversal order.
n = 3[[1,2,3],[8,9,4],[7,6,5]]Starting from position (0,0), we fill the 3×3 grid in a clockwise spiral: First row left-to-right (1,2,3), then rightmost column top-to-bottom (4,5), then bottom row right-to-left (6,7), and finally leftmost column bottom-to-top (8). The center cell receives the final value (9).
n = 1[[1]]A 1×1 grid contains only a single cell, which is filled with the value 1.
n = 4[[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]For a 4×4 grid, the outer ring is filled first (1→2→3→4→5→6→7→8→9→10→11→12), then the inner 2×2 ring (13→14→15→16) completes the spiral pattern.
Constraints