Spiral · Pattern
Clockwise Spiral
Clockwise 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.
Clockwise 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] = k; k += 1
top += 1
for i in range(top, bottom + 1): m[i][right] = k; k += 1
right -= 1
for j in range(right, left - 1, -1): m[bottom][j] = k; k += 1
bottom -= 1
for i in range(bottom, top - 1, -1): m[i][left] = k; 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] | |
Clockwise Spiral
Fill an n × n matrix by walking its perimeter inwards: right along the top, down the right side, left along the bottom, up the left side, then tighten the walls and repeat. Each step writes the next counting number, producing a tidy clockwise spiral.
The size-5 grid
A 5-by-5 matrix filled with 1 to 25: the outer ring is written first (top row left to right, right column top to bottom, bottom row right to left, left column bottom to top), the inner 3-by-3 ring continues from 17, and the centre cell receives 25 last.
Off-by-one traps
On odd sizes the final row and column passes meet in one cell; without the top <= bottom and left <= right guards that centre is written twice and the counter runs past 25.
Step by step
- Set four borders: top = 0, bottom = n - 1, left = 0, right = n - 1.
- Walk right across the top row, writing 1, 2, 3, …; then top++.
- Walk down the right column; then right--.
- Walk left across the bottom row; then bottom--.
- Walk up the left column; then left++.
- Repeat while top ≤ bottom and left ≤ right — the number counter never resets.
Complexity
When to use it
- Matrix traversal in interviews
- Border-shrink "wall" technique
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