0
0
PythonProgramBeginner · 2 min read

Python Program to Print Spiral Pattern

You can print a spiral pattern in Python by creating a 2D list and filling it in layers using top, bottom, left, right boundaries and updating them while looping until all elements are filled.
📋

Examples

Inputn = 3
Output1 2 3 8 9 4 7 6 5
Inputn = 4
Output1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
Inputn = 1
Output1
🧠

How to Think About It

To print a spiral pattern, imagine filling a square grid starting from the top-left corner moving right, then down, then left, then up, and repeating this cycle while shrinking the boundaries after each direction until all cells are filled.
📐

Algorithm

1
Create an n x n matrix filled with zeros.
2
Initialize four pointers: top, bottom, left, right to mark the current boundaries.
3
Fill the top row from left to right, then move the top boundary down.
4
Fill the right column from top to bottom, then move the right boundary left.
5
Fill the bottom row from right to left, then move the bottom boundary up.
6
Fill the left column from bottom to top, then move the left boundary right.
7
Repeat steps 3-6 until all numbers from 1 to n*n are filled.
💻

Code

python
def print_spiral(n):
    matrix = [[0]*n for _ in range(n)]
    top, bottom = 0, n-1
    left, right = 0, n-1
    num = 1
    while left <= right and top <= bottom:
        for i in range(left, right+1):
            matrix[top][i] = num
            num += 1
        top += 1
        for i in range(top, bottom+1):
            matrix[i][right] = num
            num += 1
        right -= 1
        if top <= bottom:
            for i in range(right, left-1, -1):
                matrix[bottom][i] = num
                num += 1
            bottom -= 1
        if left <= right:
            for i in range(bottom, top-1, -1):
                matrix[i][left] = num
                num += 1
            left += 1
    for row in matrix:
        print(' '.join(map(str, row)))

print_spiral(4)
Output
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
🔍

Dry Run

Let's trace n=3 through the code

1

Initialize matrix and boundaries

matrix = [[0,0,0],[0,0,0],[0,0,0]], top=0, bottom=2, left=0, right=2, num=1

2

Fill top row left to right

matrix[0][0]=1, matrix[0][1]=2, matrix[0][2]=3, num=4, top=1

3

Fill right column top to bottom

matrix[1][2]=4, matrix[2][2]=5, num=6, right=1

4

Fill bottom row right to left

matrix[2][1]=6, matrix[2][0]=7, num=8, bottom=1

5

Fill left column bottom to top

matrix[1][0]=8, num=9, left=1

6

Fill top row left to right (inner layer)

matrix[1][1]=9, num=10, top=2

StepMatrix State
After step 2[[1, 2, 3], [0, 0, 0], [0, 0, 0]]
After step 3[[1, 2, 3], [0, 0, 4], [0, 0, 5]]
After step 4[[1, 2, 3], [0, 0, 4], [7, 6, 5]]
After step 5[[1, 2, 3], [8, 0, 4], [7, 6, 5]]
After step 6[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
💡

Why This Works

Step 1: Use boundaries to control filling

The variables top, bottom, left, right mark the edges of the current layer to fill, shrinking inward after each pass.

Step 2: Fill in four directions

Fill the matrix in four steps: left to right, top to bottom, right to left, and bottom to top, covering the outer layer each time.

Step 3: Repeat until complete

Repeat the filling process while adjusting boundaries until all numbers from 1 to n*n are placed in spiral order.

🔄

Alternative Approaches

Using direction vectors
python
def spiral_with_directions(n):
    matrix = [[0]*n for _ in range(n)]
    directions = [(0,1),(1,0),(0,-1),(-1,0)]
    x = y = d = 0
    for num in range(1, n*n+1):
        matrix[x][y] = num
        dx, dy = directions[d]
        nx, ny = x+dx, y+dy
        if 0 <= nx < n and 0 <= ny < n and matrix[nx][ny] == 0:
            x, y = nx, ny
        else:
            d = (d+1) % 4
            dx, dy = directions[d]
            x, y = x+dx, y+dy
    for row in matrix:
        print(' '.join(map(str, row)))

spiral_with_directions(4)
This method uses direction vectors and checks boundaries dynamically, making the code more flexible but slightly more complex.
Recursive filling
python
def fill_spiral(matrix, top, bottom, left, right, num):
    if left > right or top > bottom:
        return
    for i in range(left, right+1):
        matrix[top][i] = num
        num += 1
    for i in range(top+1, bottom+1):
        matrix[i][right] = num
        num += 1
    if top != bottom:
        for i in range(right-1, left-1, -1):
            matrix[bottom][i] = num
            num += 1
    if left != right:
        for i in range(bottom-1, top, -1):
            matrix[i][left] = num
            num += 1
    fill_spiral(matrix, top+1, bottom-1, left+1, right-1, num)

def print_spiral_recursive(n):
    matrix = [[0]*n for _ in range(n)]
    fill_spiral(matrix, 0, n-1, 0, n-1, 1)
    for row in matrix:
        print(' '.join(map(str, row)))

print_spiral_recursive(4)
This recursive approach breaks the problem into smaller layers, but recursion depth may be a concern for large n.

Complexity: O(n^2) time, O(n^2) space

Time Complexity

The program fills each cell of the n x n matrix exactly once, so the time complexity is O(n^2).

Space Complexity

The matrix requires O(n^2) space to store the spiral pattern; no extra significant space is used.

Which Approach is Fastest?

Both boundary pointer and direction vector methods run in O(n^2) time; the boundary pointer method is simpler and more readable for beginners.

ApproachTimeSpaceBest For
Boundary pointersO(n^2)O(n^2)Simplicity and clarity
Direction vectorsO(n^2)O(n^2)Flexibility and dynamic movement
Recursive fillingO(n^2)O(n^2)Divide and conquer style, but less efficient for large n
💡
Use boundary pointers to control the spiral filling direction and avoid overwriting values.
⚠️
Forgetting to update boundaries after each direction causes infinite loops or incorrect patterns.