Python Perfect Square Spiral Pattern

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A perfect square spiral (spiral matrix) fills an n×n grid with consecutive numbers 1..n² walking clockwise around shrinking border layers.

Remember
Rule: top → right → bottom → left, then shrink boundaries

   1   2   3   4
  12  13  14   5
  11  16  15   6
  10   9   8   7     ← n = 4

Follows the growing reverse pattern in Program 61; next explore Python star patterns.

How to Solve It

Allocate a 2D list. Maintain top, bottom, left, right. Fill four sides per layer, then move those walls inward until they cross.

MethodIdeaBest for
Four-boundary spiralFill top/right/bottom/left, then shrinkLearning, interviews, exams
Fixed-width printprint(f"{value:4d}", end="")Aligned columns for multi-digit values

Pseudocode

Pseudocode
top = 0, bottom = n - 1, left = 0, right = n - 1
val = 1
while top <= bottom and left <= right:
    fill top row left→right; top = top + 1
    fill right column top→bottom; right = right - 1
    if top <= bottom:
        fill bottom row right→left; bottom = bottom - 1
    if left <= right:
        fill left column bottom→top; left = left + 1
print the grid

Cheat sheet

GoalPattern
Boundariestop = 0; bottom = n - 1; left = 0; right = n - 1
Top sidefor j in range(left, right + 1): a[top][j] = val; val += 1
Right sidefor i in range(top, bottom + 1): a[i][right] = val; val += 1
Bottom / leftSame idea reversed; guard with if top <= bottom / if left <= right
Print cellprint(f"{a[i][j]:4d}", end="")

Printing Numbers vs Starting a New Line

APIEffectUse for
print(f"{a[i][j]:4d}", end="")Stays on the same lineEach cell in a row
print()Ends the current lineAfter every row of n cells

Print cells with end="" (no newline), then call bare print() once per row — same-line vs newline output.

Live Preview

Change the grid size and the clockwise spiral updates instantly — capped at 8 so the matrix stays readable.

Whole numbers from 1 to 8. Tap a chip or type a value — the preview redraws as you go.

Live result n = 4 · 16 cells
   1   2   3   4
  12  13  14   5
  11  16  15   6
  10   9   8   7

Worked Walkthrough — Outer Layer for n = 4

Trace the first ring so the four-side order and boundary shrink are clear.

SideActionValues filled
Topa[0][0..3], then top += 11 2 3 4
Righta[1..3][3], then right -= 15 6 7
Bottoma[3][2..0], then bottom -= 18 9 10
Lefta[2..1][0], then left += 111 12

Inner 2×2 then fills 13 14 / 16 15. Total cells = n² → O(n²).

Python Programs

Three complete programs: fixed 10×10, user-input size, and a compact 4×4 demo. Use View Output to reveal sample results.

Example 1 — Fixed 10×10 Spiral

Hard-coded size — fill with four boundaries, print with width 4 (numbers 1–100).

Python
n = 10
a = [[0] * n for _ in range(n)]
top, bottom, left, right = 0, n - 1, 0, n - 1
val = 1

while top <= bottom and left <= right:
    for j in range(left, right + 1):
        a[top][j] = val
        val += 1
    top += 1

    for i in range(top, bottom + 1):
        a[i][right] = val
        val += 1
    right -= 1

    if top <= bottom:
        for j in range(right, left - 1, -1):
            a[bottom][j] = val
            val += 1
        bottom -= 1

    if left <= right:
        for i in range(bottom, top - 1, -1):
            a[i][left] = val
            val += 1
        left += 1

for i in range(n):
    for j in range(n):
        print(f"{a[i][j]:4d}", end="")
    print()

How It Works

1. Outer layer first. Top fills 1..10, right continues downward, then bottom and left close the ring.

2. Shrink inward. After each side, move that boundary so the next layer starts one cell inside.

3. Align. :4d keeps 1–100 lined up in neat columns.

Example 2 — User Input Size

Read n safely with int(input()), allocate a 2D list, then run the same spiral fill.

Python
try:
    n = int(input("Enter size n: "))
except ValueError:
    print("Please enter a positive integer.")
    raise SystemExit

if n <= 0:
    print("Please enter a positive integer.")
    raise SystemExit

a = [[0] * n for _ in range(n)]
top, bottom, left, right = 0, n - 1, 0, n - 1
val = 1

while top <= bottom and left <= right:
    for j in range(left, right + 1):
        a[top][j] = val
        val += 1
    top += 1

    for i in range(top, bottom + 1):
        a[i][right] = val
        val += 1
    right -= 1

    if top <= bottom:
        for j in range(right, left - 1, -1):
            a[bottom][j] = val
            val += 1
        bottom -= 1

    if left <= right:
        for i in range(bottom, top - 1, -1):
            a[i][left] = val
            val += 1
        left += 1

for i in range(n):
    for j in range(n):
        print(f"{a[i][j]:4d}", end="")
    print()

How It Works

1. Prompt and validate. Catch ValueError and require n > 0 before allocating the list.

2. Same core. Boundary fill matches Example 1 — only n comes from the user.

3. Safer input tip. Cap demos for readable console output:

Safer input
try:
    n = int(input("Enter size n: "))
except ValueError:
    print("Enter a whole number from 1 to 20.")
    raise SystemExit

if n < 1 or n > 20:
    print("Enter a whole number from 1 to 20.")
    raise SystemExit

Example 3 — Compact 4×4 Trace

Sixteen cells — easy to dry-run every side of the outer and inner layers on paper.

Python
n = 4
a = [[0] * n for _ in range(n)]
top, bottom, left, right = 0, n - 1, 0, n - 1
val = 1

while top <= bottom and left <= right:
    for j in range(left, right + 1):
        a[top][j] = val
        val += 1
    top += 1

    for i in range(top, bottom + 1):
        a[i][right] = val
        val += 1
    right -= 1

    if top <= bottom:
        for j in range(right, left - 1, -1):
            a[bottom][j] = val
            val += 1
        bottom -= 1

    if left <= right:
        for i in range(bottom, top - 1, -1):
            a[i][left] = val
            val += 1
        left += 1

for i in range(n):
    for j in range(n):
        print(f"{a[i][j]:4d}", end="")
    print()

How It Works

1. Two layers. Outer ring uses 1–12; inner 2×2 uses 13–16.

2. Guards matter. The if top <= bottom / if left <= right checks prevent double-filling when only one row or column remains.

3. Scale up next. Once the small demo is clear, use Examples 1–2 for 10×10 or user input.

Edge Cases & Pitfalls

Check these before calling the solution done.

no guards

Double-filled middle

On odd n, skipping the if top <= bottom / if left <= right checks can overwrite the center cell.

:4d only

Crooked columns

Without :4d, single-digit and three-digit numbers misalign. Keep a fixed field width.

print inside

Broken rows

If bare print() sits inside the column loop, each cell lands on its own line. Call it only after the row finishes.

n = 1

Single cell

Output is just 1 — a good sanity check for the while condition.

wrong side order

Not a spiral

Keep the clockwise order top → right → bottom → left. Swapping sides breaks the ring.

ValueError

Validate before allocate

Use try/except ValueError and require n > 0 before building the 2D list — bad input should not crash.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(n²) list
Compact 4×4 (Example 3)O(n²)O(n²) list

Every cell is written once and printed once → O(n²) time. The 2D list uses O(n²) space.

Key Takeaways

  • Four sides per layer: top → right → bottom → left, then shrink.
  • Guard odd centers: check top <= bottom and left <= right before the reverse sides.
  • Align with width 4: print(f"{v:4d}", end="") keeps multi-digit columns neat.
  • Complexity: O(n²) time and O(n²) list space for an n×n fill.

One line: walk each ring clockwise with shrinking top/bottom/left/right until 1..n² is filled.

Frequently Asked Questions

It prints a perfect square spiral (spiral matrix) filled with numbers 1..n² in a clockwise spiral — e.g. 10×10 holds 1–100.
Those four variables mark the current layer. After filling a side, you move that boundary inward and continue.
Using print(f"{value:4d}", end="") prints each number in a fixed width of 4 characters, keeping columns aligned.
Program 61 uses a while loop on one number. Program 62 fills an n×n grid with a 2D list and boundary-based spiral loops.
Yes. This is a classic spiral matrix generation exercise: fill the grid while shrinking boundaries.
Yes. The boundary approach works for any positive n, both odd and even.
A 1×1 grid holds only the value 1 — one cell, one layer.
O(n²) for an n×n grid because each cell is filled and printed once.

Did you know?

A perfect square spiral fills an n×n grid with numbers 1..n² by walking each border layer clockwise and tightening boundaries — runtime is O(n²).

Next: Python Star Patterns

Continue with star-pattern tutorials after finishing the number series.

Star patterns →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful