Center-Outward Number Spiral
Problem statement
Given a positive odd integer n, construct an n by n matrix containing every integer from 1 through n * n.
Place 1 in the center cell. Continue with consecutive integers while moving in an outward spiral:
- Move down first.
- Turn right relative to the current movement after completing each leg, so the directions repeat as down, left, up, right.
- Increase the leg length after every two legs.
- Stop after placing
n * n.
Return the completed matrix.
Function
centerOutwardSpiral(n: int) → int[][]Examples
Example 1
n = 3return = [[5,6,7],[4,1,8],[3,2,9]]The spiral starts at the center with 1, moves down to 2, then expands through left, up, and right turns until 9 reaches the bottom-right corner.
Example 2
n = 1return = [[1]]A one-cell matrix contains only the center value 1.
Constraints
1 <= n <= 99nis odd.