Perfect Square Spiral Numbers (10×10) in Python

Intermediate
⏱️ 9 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
2D Arrays

What You’ll Learn

How to generate a clockwise spiral of numbers in a square grid using Python.

You’ll learn the core idea: maintain four boundaries (top, bottom, left, right) and shrink them after completing each layer of the spiral.

⭐ Pattern Output

For n = 10, the pattern looks like this:

Output
  1   2   3   4   5   6   7   8   9  10\n 36  37  38  39  40  41  42  43  44  11\n 35  64  65  66  67  68  69  70  45  12\n 34  63  84  85  86  87  88  71  46  13\n 33  62  83  96  97  98  89  72  47  14\n 32  61  82  95 100  99  90  73  48  15\n 31  60  81  94  93  92  91  74  49  16\n 30  59  80  79  78  77  76  75  50  17\n 29  58  57  56  55  54  53  52  51  18\n 28  27  26  25  24  23  22  21  20  19
1

Complete Python Program

Fill the matrix layer by layer using boundary pointers (top, bottom, left, right).

Python
n = 10
grid = [[0] * n for _ in range(n)]

top, bottom = 0, n - 1
left, right = 0, n - 1
val = 1

while top <= bottom and left <= right:
    # Top row (left -> right)
    for j in range(left, right + 1):
        grid[top][j] = val
        val += 1
    top += 1

    # Right column (top -> bottom)
    for i in range(top, bottom + 1):
        grid[i][right] = val
        val += 1
    right -= 1

    # Bottom row (right -> left)
    if top <= bottom:
        for j in range(right, left - 1, -1):
            grid[bottom][j] = val
            val += 1
        bottom -= 1

    # Left column (bottom -> top)
    if left <= right:
        for i in range(bottom, top - 1, -1):
            grid[i][left] = val
            val += 1
        left += 1

for row in grid:
    print(" ".join(f"{x:3d}" for x in row))

🧠 How It Works

1

Create an n×n grid

grid = [[0] * n for _ in range(n)] allocates the matrix we’ll fill.

Setup
2

Track 4 boundaries

Use top, bottom, left, right to mark the current layer.

Boundaries
3

Fill 4 sides (clockwise)

Write the top row, right column, bottom row, and left column in order, then shrink boundaries to move inward.

Layer fill
4

Stop at the center

The loop ends when top > bottom or left > right, meaning all cells are filled.

Finish
=

Spiral layers

Each layer writes a rectangle border, then moves one step inward. Total writes are , so time complexity is O(n²).

2

Variation — User Input Version

Let the user choose the grid size at runtime:

Python
n = int(input("Enter the grid size (n): "))
grid = [[0] * n for _ in range(n)]

top, bottom = 0, n - 1
left, right = 0, n - 1
val = 1

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

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

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

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

for row in grid:
    print(" ".join(f"{x:3d}" for x in row))

💡 Tips for Enhancement

Try These

  • Start from a different number (for example, start at 0 or 101)
  • Reverse direction (counter-clockwise) by changing fill order
  • Fill inward from the center by reversing the numbering
  • Use f"{x:4d}" formatting for bigger spirals to keep columns aligned
  • Validate input (reject n < 1) before building the grid

Avoid

  • Forgetting to update boundaries after filling a side (leads to infinite loops)
  • Overwriting cells by filling a side when its boundary has already crossed
  • Printing the grid without fixed-width formatting (columns will misalign)
  • Mixing up row and column indices when assigning values

Key Takeaways

1

Use 4 boundaries (top, bottom, left, right) to manage layers.

2

Each loop iteration fills up to four sides, then moves inward.

3

Every cell is assigned once, so the runtime is O(n²).

4

This technique generalizes to spiral traversals and layered matrix problems.

❓ Frequently Asked Questions

A 10×10 grid has 100 cells, so filling it sequentially assigns values 1 through 100.
After writing a side, we move that boundary inward (for example, top += 1). Guard checks like if top <= bottom stop extra passes when the spiral reaches the center.
Yes. For odd n the spiral ends at a single center cell; for even n it ends in a 2×2 center region. The boundary conditions handle both.
O(n²) because we assign and print values.

Explore More Python Number Patterns!

From triangles to spirals—build confidence with loops, boundaries, and indexing.

All Number Patterns →
Did you know?

A spiral fill assigns exactly values. For n = 10, that’s 100 assignments—one for each cell in the grid.

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