Shape Rule
Spiral matrix
Numbers flow clockwise around each border ring — 1..10 on the outer ring of a 10×10 grid, then inward to 100 at the center.

Program 62 generates a perfect square spiral: fill an $n×$n grid with numbers 1..n² clockwise, layer by layer, using a 2D array and shrinking boundaries. This tutorial covers the spiral fill order, boundary variables, a live preview, worked PHP examples, edge cases, and O(n²) complexity.
Spiral matrix
Numbers flow clockwise around each border ring — 1..10 on the outer ring of a 10×10 grid, then inward to 100 at the center.
2D array grid
$a = array_fill(0, $n, array_fill(0, $n, 0)) stores each cell before printing with fixed-width formatting.
low / high
$low and $high mark the current square ring — increment/decrement after each layer to move inward.
Top, right, bottom, left
Each layer fills top row, right column, bottom row, left column — incrementing counter $n each cell.
3–12 size
Pick grid size and draw the spiral matrix in the browser.
Complexity
Every cell visited once — 10×10 = 100 cells, hence O(n²) time and space.
A perfect square spiral (spiral matrix) fills an $n×$n grid with consecutive integers flowing clockwise around shrinking border rings. With $n = 10, you get a 10×10 grid numbered 1 through 100.
In PHP allocate $a = array_fill(0, 10, array_fill(0, 10, 0)), walk each layer with $low/$high boundaries, fill four sides per ring, then print with printf("%4d", ...) fixed-width formatting.
Spiral-matrix logic appears in interviews, grid simulations, and image processing — it bridges simple loops to 2D array reasoning.
$a = array_fill(0, $n, array_fill(0, $n, 0)) stores the grid.
$low/$high track each ring.
Program 61 works on one number; Program 62 fills a 2D grid.
Last number pattern — continue to PHP Star Patterns next.
In short: allocate $a = array_fill(0, $n, array_fill(0, $n, 0)), fill four sides per layer with shrinking boundaries, print with printf("%4d", ...).
Given grid size $n = 10, fill an $n×$n array with numbers 1..n² in a clockwise spiral starting from the top-left corner.
// $n = 4 (compact sample)
// 1 2 3 4
//12 13 14 5
//11 16 15 6
//10 9 8 7 | Item | Type | Description |
|---|---|---|
$n | int | Grid dimension — 10 in the fixed demo (10×10 = 100 cells). |
$a[$i][$j] | 2D array | 2D array storing each cell value. |
$low, $high | int | Current layer boundaries — start 0 and n−1, move inward each ring. |
| Fill counter | int | Starts at 1, increments for every cell placed. |
| Layers | int | n/2 rings for even n — 5 layers when n = 10. |
| Print format | string | printf("%4d", $value) fixed width keeps columns aligned. |
create n×n array
set low=0, high=n-1, val=1
while low <= high:
fill top row left→right
fill right column top→bottom
fill bottom row right→left
fill left column bottom→top
low++, high--
print array with fixed width | Approach | Idea | Best for |
|---|---|---|
| low / high rings | Outer loop over layers, four inner loops per side | Fixed 10×10 demo (Example 1) |
| top/bottom/left/right | While loop shrinks all four boundaries | Configurable size (Example 2) |
| Compact trace | n = 4 on paper first | Quick dry-runs |
| Direction array | Simulate walk with dx/dy turns | Alternative interview solution |
| Wider print width | {0, 5} or more when n² > 9999 | Large grids |
| Goal | Pattern |
|---|---|
| Allocate | $a = array_fill(0, $n, array_fill(0, $n, 0)); |
| Layer loop | for ($layer = 0; $layer < ($n+1)/2; $layer++, $low++, $high--) |
| Fill order | Top row → right col → bottom row → left col |
| Print cell | printf("%4d", $a[$i][$j]); |
Same spiral matrix — three ways to set grid size and trace the fill logic.
$n = 10Hard-coded with low/high rings
top/bottom/left/rightConfigurable n from console
n = 4Quick dry-run on paper
4 per layerTop, right, bottom, left
printf("%4d")Fixed-width columns
Reach for this pattern when teaching 2D arrays, boundary control, and O(n²) grid algorithms in PHP.
Natural finale for the number-pattern series — graduate from 1D loops to 2D spiral filling.
Classic spiral-matrix question — explain boundary shrinking before coding.
Index reasoning with $a[$row][$col] and nested loop bounds.
Continue to C star-pattern programs after mastering this grid exercise.
Very large grids produce huge console output — cap n for demos.
Key benefit: one program that locks in 2D arrays, boundary control, and O(n²) grid thinking.
Enter grid size between 3 and 8 and draw the perfect square spiral matrix in the browser.
Three complete PHP programs — fixed 10×10, fgets(STDIN) size input, and a refactored fill_spiral helper with print_matrix. Click View Output to reveal sample console results.
Hard-coded $n = 10 — four edge loops per layer with $low and $high.
<?php
$n = 10;
$a = array_fill(0, $n, array_fill(0, $n, 0));
$low = 0;
$high = $n - 1;
$val = 1;
for ($layer = 0; $layer < (int)(($n + 1) / 2); $layer++, $low++, $high--) {
for ($j = $low; $j <= $high; $j++, $val++) $a[$low][$j] = $val;
for ($i = $low + 1; $i <= $high; $i++, $val++) $a[$i][$high] = $val;
for ($j = $high - 1; $j >= $low; $j--, $val++) $a[$high][$j] = $val;
for ($i = $high - 1; $i > $low; $i--, $val++) $a[$i][$low] = $val;
}
echo "Perfect Square Spiral" . PHP_EOL;
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++)
printf("%4d", $a[$i][$j]);
echo PHP_EOL;
} Read $n from the user and fill an $n×$n spiral matrix.
<?php
echo "Enter matrix size n: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input) || (int) $input <= 0) {
echo "Please enter a positive integer." . PHP_EOL;
exit(1);
}
$n = (int) $input;
$a = array_fill(0, $n, array_fill(0, $n, 0));
$low = 0;
$high = $n - 1;
$val = 1;
for ($layer = 0; $layer < (int)(($n + 1) / 2); $layer++, $low++, $high--) {
for ($j = $low; $j <= $high; $j++, $val++) $a[$low][$j] = $val;
for ($i = $low + 1; $i <= $high; $i++, $val++) $a[$i][$high] = $val;
for ($j = $high - 1; $j >= $low; $j--, $val++) $a[$high][$j] = $val;
for ($i = $high - 1; $i > $low; $i--, $val++) $a[$i][$low] = $val;
}
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++)
printf("%4d", $a[$i][$j]);
echo PHP_EOL;
} Refactor layer logic into fill_spiral and print with print_matrix.
<?php
function fill_spiral(&$a, $n) {
$low = 0;
$high = $n - 1;
$val = 1;
for ($layer = 0; $layer < (int)(($n + 1) / 2); $layer++, $low++, $high--) {
for ($j = $low; $j <= $high; $j++, $val++) $a[$low][$j] = $val;
for ($i = $low + 1; $i <= $high; $i++, $val++) $a[$i][$high] = $val;
for ($j = $high - 1; $j >= $low; $j--, $val++) $a[$high][$j] = $val;
for ($i = $high - 1; $i > $low; $i--, $val++) $a[$i][$low] = $val;
}
}
function print_matrix($a, $n) {
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++)
printf("%4d", $a[$i][$j]);
echo PHP_EOL;
}
}
$n = 10;
$a = array_fill(0, $n, array_fill(0, $n, 0));
fill_spiral($a, $n);
print_matrix($a, $n); $a = array_fill(0, $n, array_fill(0, $n, 0)) holds all spiral values before printing.
$low = 0, $high = $n - 1 (or top/bottom/left/right) mark the current ring.
Top row, right column, bottom row, left column — incrementing counter each cell.
printf("%4d", $a[$i][$j]) keeps columns aligned.
n² cells filled and printed — O(n²) time and space.
n = 4Trace the first (outer) ring of a 4×4 spiral — values 1 through 12 on the border, then inner 2×2 fills 13—16.
| Side | Cells filled | Values placed |
|---|---|---|
| Top row | (0,0)..(0,3) | 1, 2, 3, 4 |
| Right column | (1,3)..(3,3) | 5, 6, 7 |
| Bottom row | (3,2)..(3,0) | 8, 9, 10 |
| Left column | (2,0)..(1,0) | 11, 12 |
| Inner 2×2 | Second layer | 13, 14, 15, 16 |
For $n = 10, repeat this four-side pattern for 5 concentric rings until the center cell holds 100.
Where spiral-matrix filling shows up beyond the homework prompt.
$a = array_fill(0, $n, array_fill(0, $n, 0)) with row/column indexing — a visual grid exercise for beginners.
Example: trace which cells get values 1—4 on the outer ring of a 4×4 grid.
Classic spiral-matrix question — explain boundary shrinking before coding.
Example: walk through top → right → bottom → left for one layer.
Final number-pattern program — graduates from 1D loops to 2D boundary control.
Example: compare Program 61’s while loop with nested spiral loops here.
After mastering grids, move to C star-pattern programs for shape-based output.
Example: continue to PHP Star Patterns next.
Every cell visited once — concrete quadratic complexity for grid algorithms.
Example: 10×10 = 100 cells filled and printed.
Spiral traversal appears in image processing, maze generation, and game maps.
Example: adapt the fill order to visit cells in spiral order without storing all values.
Pro Tip: dry-run a 4×4 grid on paper before attempting 10×10 — the four-side pattern repeats per layer.
Why spiral-matrix exercises belong in every beginner C course.
Students see numbers flow around the grid — wrong boundary logic shows up immediately.
Four inner loops per layer reinforce index bounds and loop direction (forward/backward).
Spiral matrix is a standard coding question — this tutorial maps directly to it.
Same boundary approach works for odd and even sizes — only print width may need adjustment.
Pro Tip: trace the first layer of n = 4 on paper — values 1—12 on the border before the inner 2×2 fills 13—16.
Small habits that keep spiral-matrix code clean.
Top → right → bottom → left — skipping or reordering breaks the spiral.
Start right column at $low + 1, bottom row at $high - 1 — corners are already filled.
printf("%4d", $value) keeps columns aligned for $n up to 10×10.
When using top/bottom/left/right, check top <= bottom before bottom and left fills.
Dry-run a 4×4 grid on paper before coding the 10×10 demo.
Pro Tip: if numbers jump or repeat, check whether a side loop includes an already-filled corner cell.
Mistakes that commonly break spiral-matrix programs.
Starting every side at the same corner overwrites cells — spiral breaks at turns.
→ Skip the first cell on right, bottom, and left sides after the top row.
Running too many or too few outer iterations leaves cells empty or overwritten.
→ Use n/2 layers for even n — 5 rings when n = 10.
On odd n or the last layer, bottom/left fills may run when boundaries crossed.
→ Wrap bottom and left fills with if (top <= bottom) checks.
Printing without fixed width makes large numbers shift columns.
→ Use printf("%4d", ...) or wider when $n² exceeds 9999.
Swapping $a[$i][$j] indices fills transposed or scrambled output.
→ Top row uses fixed row i, varying column j.
Check these inputs before calling the solution done.
Grid holds only value 1 — one layer, one print.
Four cells in one layer — good minimal test case.
Center cell 9 filled in the innermost layer — verify boundary guards.
Reject with a message — do not allocate a zero-length array.
Unchecked fgets(STDIN) leaves $n unset — check with is_numeric($input).
Cap n for demos — O(n²) cells means O(n²) print lines.
Try these variations to lock in the spiral pattern.
$low++ and $high-- after four sides.Quick Takeaway: allocate $a = array_fill(0, $n, array_fill(0, $n, 0)), fill four sides per layer, tighten boundaries, print with printf("%4d", ...).
| Program | Time | Extra space |
|---|---|---|
| Fixed 10×10 (Example 1) | O(n²) — n = 10, 100 cells | O(n²) for the array |
| User input (Example 2) | O(n²) | O(n²) |
| Compact 4×4 (Example 3) | O(n²) — n = 4, 16 cells | O(n²) |
The perfect square spiral is a capstone 2D-array exercise: boundary control, four-side fills, and O(n²) grid thinking. Master the fixed 10×10 version, then try user input with configurable n and the compact 4×4 trace.
Practice the three examples above, then continue to PHP Star Patterns — the next chapter after number patterns.
Fill top → right → bottom → left per layer, tighten boundaries, print with fixed width — validate n when reading from the console.
printf("%4d", ...) for aligned columns$a[$i][$j]Print the perfect square spiral the beginner-friendly way.
Fill clockwise per layer
Definition2D array stores grid
StructureTop, right, bottom, left
Order/ shrink inward
O(n²) time & space
AnalysisFills n×n matrix in spiral order using $low/$high boundaries — top, right, bottom, left edges per layer. O(n²) time and space.
Number patterns complete — move on to star-shaped output programs.
12 people found this page helpful