Given n, build an n by n matrix filled with the numbers 1 to n squared, in spiral order.
DSA Animator › DSA Revision › Matrix › Spiral Matrix II
Remember: the spiral writer is the spiral reader with a counter. Four sides, then shrink. The video solves Spiral Matrix II (LeetCode 59, Medium) with the Boundary Traversal pattern from the Matrix topic, and you can replay every step in the interactive Spiral Matrix II animation.
Given n, build an n by n matrix filled with the numbers 1 to n squared, in spiral order.
For n equal to 3, the matrix is 1 2 3, then 8 9 4, then 7 6 5.
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.
Fill the top row with 1, 2, 3. Fill down the right column with 4 and 5. Fill the bottom row backwards with 6 and 7. Fill up the left column with 8. Only the center is left, and it gets 9. The matrix is complete.
In code, create an n by n array, and set the four boundaries. Loop while the counter is at most n squared. Fill each side, increasing the counter, and shrink that boundary. Every cell is written once, so it's O of n squared time.
Remember: the spiral writer is the spiral reader with a counter. Four sides, then shrink.