Spiral · Pattern
Inward Spiral
Inward Spiral
SpiralSymbol pattern, solid style, size 5. Changing the rubric, style or size above re-shapes the loops — the structure stays identical while only the printed value or the cell filter changes.
Inward Spiral · output
Symbol · Solid · size 5
n = 5
m = [[0] * n for _ in range(n)]
k = 1
top, bottom, left, right = 0, n - 1, 0, n - 1
while top <= bottom and left <= right:
for j in range(left, right + 1): m[top][j] = (n * n - k + 1); k += 1
top += 1
for i in range(top, bottom + 1): m[i][right] = (n * n - k + 1); k += 1
right -= 1
for j in range(right, left - 1, -1): m[bottom][j] = (n * n - k + 1); k += 1
bottom -= 1
for i in range(bottom, top - 1, -1): m[i][left] = (n * n - k + 1); k += 1
left += 1
for row in m:
for x in row:
print(x, end='')
print(' ', end='')
print()Behind the Scenes Execution
registers · line tracking · call stack · memory regions| Address | Variable | Value |
|---|---|---|
| Stack (4) | ||
| 0x200 | n | 5 |
| 0x204 | i | -1 |
| 0x208 | j | -1 |
| 0x20C | count | 0 |
| String Pool (static) (2) | ||
| 0x400000 | pool["*"] | * |
| 0x400008 | pool["\n"] | \n |
| Heap (5) | ||
| 0x3000 | grid[0] | |
| 0x3020 | grid[1] | |
| 0x3040 | grid[2] | |
| 0x3060 | grid[3] | |
| 0x3080 | grid[4] | |
Inward Spiral
The spiral is still filled by walking the shrinking borders, but the numbering runs from the outside value n·n down to 1 — the largest number lives in the centre. Great for seeing that start/target values are just parameters.
The size-5 grid
The 5-by-5 matrix is filled from 25 down to 1, so the top-left corner holds 25 and the centre cell holds 1. The borders still shrink clockwise; the only difference is that the counter is written before it is decremented.
Off-by-one traps
Decrementing first skips 25 and leaves 0 in the centre; writing the value then subtracting keeps the whole 1 to 25 range intact.
Step by step
- Set the four borders.
- Start the counter at n·n.
- Walk the same four edges clockwise, but write the counter and then DECREASE it.
- Shrink the borders after every edge.
- Finish when the borders collapse — the middle holds value 1.
Complexity
When to use it
- Descending counters
- Reusing the spiral walk
grid[r] rows in the Heap region and the i / j / count registers on the Stack — every printed character is one write to the grid.Recommended resourcesAffiliate links · may earn us a commission