Spiral Matrix II in Python

The Spiral Matrix II problem involves generating a square matrix filled with numbers from 1 to n² in spiral order. Starting from the top-left corner, we fill the matrix by moving right, down, left, and up in a spiral pattern until all positions are filled.

Algorithm

The spiral filling process follows these steps:

  • Initialize boundary variables: row1, col1 (top-left) and row2, col2 (bottom-right)
  • Create an n×n matrix filled with zeros
  • Fill the matrix in four directions: right ? down ? left ? up
  • After completing each spiral layer, adjust the boundaries inward
  • Continue until all n² numbers are placed

Example

Let's implement the spiral matrix generation for n = 4:

class Solution:
    def generateMatrix(self, n):
        row1 = 0
        col1 = 0
        row2 = n
        col2 = n
        result = [[0 for i in range(n)] for j in range(n)]
        num = 1
        
        while num <= n**2:
            # Fill top row (left to right)
            for i in range(col1, col2):
                result[row1][i] = num
                num += 1
            if num > n**2:
                break
            
            # Fill right column (top to bottom)
            for i in range(row1 + 1, row2):
                result[i][col2 - 1] = num
                num += 1
            if num > n**2:
                break
            
            # Fill bottom row (right to left)
            for i in range(col2 - 2, col1 - 1, -1):
                result[row2 - 1][i] = num
                num += 1
            if num > n**2:
                break
            
            # Fill left column (bottom to top)
            for i in range(row2 - 2, row1, -1):
                result[i][col1] = num
                num += 1
            
            # Move to inner layer
            row1 += 1
            row2 -= 1
            col1 += 1
            col2 -= 1
        
        return result

# Test the solution
solution = Solution()
matrix = solution.generateMatrix(4)

# Print the matrix in readable format
for row in matrix:
    print(row)

The output shows the 4×4 spiral matrix:

[1, 2, 3, 4]
[12, 13, 14, 5]
[11, 16, 15, 6]
[10, 9, 8, 7]

Visual Representation

1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Right ? Down ? ? Left ? Up

How It Works

The algorithm maintains four boundary variables and fills the matrix in layers:

  1. Right traversal: Fill the top row from left to right
  2. Down traversal: Fill the right column from top to bottom
  3. Left traversal: Fill the bottom row from right to left
  4. Up traversal: Fill the left column from bottom to top

After each complete spiral, the boundaries shrink inward by 1, creating the next inner layer.

Time and Space Complexity

Time Complexity: O(n²) - We visit each cell exactly once
Space Complexity: O(n²) - For the result matrix

Conclusion

The spiral matrix generation uses boundary tracking to fill a matrix layer by layer in spiral order. This approach ensures all n² positions are filled systematically from outside to inside.

Updated on: 2026-03-25T07:56:02+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements