A perfect square spiral fills an n × n grid with numbers 1..n² in a clockwise path — outer ring first, then the next ring inward.
Remember
Rule: for each layer [low..high]
top → right → bottom → left
then low++, high--
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9 ← n = 5
Finale of the Java number-pattern series — graduate from 1D loops (Program 61) to a full 2D spiral matrix.
Approach
How to Solve It
Allocate a 2D array, walk four edges per layer with shrinking low/high, then print with fixed width.
Method
Idea
Best for
Fixed n
Hard-coded 10×10 fill + print
Labs and demos
Scanner input
Same fill; read n at runtime
Interactive practice
fillSpiral helper
Separate fill and print methods
Cleaner structure
Pseudocode
Pseudocode
a = new int[n][n]
low = 0, high = n - 1, val = 1
for each layer while low <= high:
for j = low to high: a[low][j] = val++ // top
for i = low+1 to high: a[i][high] = val++ // right
for j = high-1 down to low: a[high][j] = val++ // bottom
for i = high-1 down to low+1: a[i][low] = val++ // left
low++; high--
print each a[i][j] with width 4
Cheat sheet
Goal
Pattern
Allocate
int[][] a = new int[n][n];
Bounds
int low = 0, high = n - 1;
Layers
(n + 1) / 2 rings
Avoid double corners
Right starts at low+1; left ends at low+1
Align columns
System.out.printf("%4d", a[i][j]);
End row
System.out.println();
Printing Numbers vs Starting a New Line
API
Effect
Use for
System.out.printf / print
Stays on the same line
Each cell in a row
System.out.println
Ends the line
After each matrix row
Build the row with printf, then break once.
Try it
Live Preview
Change n and the perfect square spiral updates instantly.
Whole numbers from 3 to 8. Tap a chip or type a value — the preview redraws as you go.
1. Separate concerns.fillSpiral only writes values; printMatrix only formats them.
2. Same algorithm. Layer count and edge loops match Examples 1 and 2.
3. Reuse. Call fillSpiral from tests or other mains without duplicating the ring logic.
Edge Cases & Pitfalls
Check these before calling the solution done.
Double corner
Wrong bounds
Right must start at low+1; left must stop before low. Overlapping corners overwrite values.
Forget shrink
Infinite / stuck layer
Always low++ and high-- after the four edges, or the same ring repeats.
n = 1
Single cell
Output is just 1 — one layer, top loop only.
Odd n
Center cell
Innermost layer is one cell (e.g. 25 for n = 5). Loops still work.
No printf
Misaligned columns
Two- and three-digit numbers need fixed width (%4d) or the grid looks skewed.
n ≤ 0
Bad allocate
Reject non-positive sizes before new int[n][n].
Analysis
Time and Space Complexity
Program
Time
Extra space
Examples 1–3
O(n²)
O(n²) for the matrix
Every cell is written once → n² assignments. The 2D array itself uses O(n²) memory.
Remember
Key Takeaways
Rule: fill top → right → bottom → left, then shrink low/high.
Corners: skip already-written corners on right and left edges.
Layers:(n + 1) / 2 rings cover the whole square.
Complexity:O(n²) time and space for size n.
One line: walk each ring of the square clockwise, then move one layer inward.
Frequently Asked Questions
It fills an n×n (perfect square) grid with numbers 1..n² in a clockwise spiral, starting at the top-left and moving inward layer by layer.
They mark the current layer’s top/bottom row and left/right column. After filling four edges, increment low and decrement high to shrink the active rectangle.
The top row already wrote the top-right corner at (low, high). Starting at low + 1 avoids writing that cell twice.
Yes. Allocate int[n][n] and run (n + 1) / 2 layers. The same four edge loops work for any positive n — see Example 2.
O(n²) — every cell is assigned exactly once, so work grows with the number of cells.
Yes. Reorder the four edge fills and adjust loop bounds so corners are not duplicated.
The innermost layer is a single cell. The last loops still work; for n=5 the center is 25.
Call sc.hasNextInt() before sc.nextInt() and validate n > 0 so bad input does not throw InputMismatchException.
🤔
Did you know?
Fills an n×n matrix in spiral order using low/high boundaries — top, right, bottom, left edges per layer. O(n²) time and space.