Given a positive integer n, generate an n × n matrix filled with elements from 1 to n² in spiral order (clockwise from the top-left).
n = 3[[1,2,3],[8,9,4],[7,6,5]]n = 4[[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]top=0, bottom=n-1, left=0, right=n-1, num=1mat[top][c] = num++, then top++mat[r][right] = num++, then right--mat[bottom][c] = num++, then bottom--mat[r][left] = num++, then left++num > n² — boundaries shrink inward each passThe four boundaries (top, right, bottom, left) define the current unfilled shell. After traversing each edge we shrink that boundary inward, so the next iteration fills the next inner ring. This is identical to reading Spiral Matrix I — except we write sequential integers instead of reading existing values.
This is Spiral Matrix in reverse: instead of reading in spiral order, you write. The same four boundaries make it simple.
Keep a counter that starts at 1. Fill the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top. Shrink each boundary after its side is filled, until the counter passes n squared.
The spiral writer is the spiral reader with a counter. Four sides, then shrink.
Run the animation above on your own input, or watch the 1:11 video explanation of Spiral Matrix II with a dry run and Java code.