Problem 492
Spiral Matrix II
Medium · 20 pts · Matrix, Simulation
Problem
Build an N x N matrix filled with the numbers 1 to N² in spiral order: start at the top-left corner, go right along the top row, then down the right column, then left along the bottom row, then up the left column, and keep spiralling inwards until every cell is filled. Print the matrix.
Input
A single integer N.
Output
Print the matrix: N lines of N integers.
Constraints
1 <= N <= 30
Example input
3
Example output
1 2 3 8 9 4 7 6 5
Explanation
For N = 3, the numbers 1 to 9 spiral inwards clockwise: the top row is 1 2 3, then 4 and 5 go down the right side and along the bottom, and 9 ends in the centre, giving 1 2 3 / 8 9 4 / 7 6 5.