Program to find area of largest square of 1s in a given matrix in python

Suppose we have a binary matrix, we have to find the area of the largest square of 1s in that given matrix using dynamic programming.

Problem Understanding

Given a binary matrix containing only 0s and 1s, we need to find the area of the largest square submatrix that contains only 1s.

For example, if the input matrix is ?

1 0 0 0 0 1 1 0 0 0 0 0 1 1 0 1 1 1 1 0 0 0 1 1 1 1 0 0 Largest square of 1s (4×4) Area = 16

The output will be 16 (area of 4×4 square).

Algorithm

We use dynamic programming where each cell stores the side length of the largest square ending at that position ?

  • Initialize result as 0
  • Process first row and first column separately
  • For each cell (i,j), if it contains 1, calculate the minimum of its left, top, and diagonal neighbors, then add 1
  • Keep track of the maximum side length found
  • Return the square of maximum side length (area)

Implementation

def largest_square_area(matrix):
    if not matrix or not matrix[0]:
        return 0
    
    rows, cols = len(matrix), len(matrix[0])
    max_side = 0
    
    # Check first row
    for i in range(rows):
        max_side = max(max_side, matrix[i][0])
    
    # Check first column
    for j in range(cols):
        max_side = max(max_side, matrix[0][j])
    
    # Process remaining cells
    for i in range(1, rows):
        for j in range(1, cols):
            if matrix[i][j] == 1:
                # Find minimum of three neighbors and add 1
                matrix[i][j] = min(
                    matrix[i-1][j],     # top
                    matrix[i-1][j-1],   # diagonal
                    matrix[i][j-1]      # left
                ) + 1
                max_side = max(max_side, matrix[i][j])
    
    return max_side * max_side

# Test the function
matrix = [
    [1, 0, 0, 0, 0, 1, 1],
    [0, 0, 0, 0, 0, 1, 1],
    [0, 1, 1, 1, 1, 0, 0],
    [0, 1, 1, 1, 1, 0, 0],
    [0, 1, 1, 1, 1, 0, 0],
    [0, 1, 1, 1, 1, 0, 0]
]

result = largest_square_area(matrix)
print(f"Area of largest square: {result}")
Area of largest square: 16

How It Works

The algorithm transforms the matrix by replacing each 1 with the side length of the largest square ending at that position ?

# Example of matrix transformation
original = [
    [0, 1, 1, 1],
    [0, 1, 1, 1], 
    [0, 1, 1, 1]
]

# After processing, matrix becomes:
# [0, 1, 1, 1]
# [0, 1, 2, 2]  
# [0, 1, 2, 3]

def show_transformation(matrix):
    import copy
    original = copy.deepcopy(matrix)
    
    rows, cols = len(matrix), len(matrix[0])
    max_side = 0
    
    for i in range(rows):
        max_side = max(max_side, matrix[i][0])
    for j in range(cols):
        max_side = max(max_side, matrix[0][j])
        
    for i in range(1, rows):
        for j in range(1, cols):
            if matrix[i][j] == 1:
                matrix[i][j] = min(matrix[i-1][j], matrix[i-1][j-1], matrix[i][j-1]) + 1
                max_side = max(max_side, matrix[i][j])
    
    print("Original matrix:")
    for row in original:
        print(row)
    print("\nAfter transformation:")
    for row in matrix:
        print(row)
    print(f"\nLargest square side: {max_side}")
    print(f"Area: {max_side * max_side}")

test_matrix = [
    [0, 1, 1, 1],
    [0, 1, 1, 1], 
    [0, 1, 1, 1]
]

show_transformation(test_matrix)
Original matrix:
[0, 1, 1, 1]
[0, 1, 1, 1]
[0, 1, 1, 1]

After transformation:
[0, 1, 1, 1]
[0, 1, 2, 2]
[0, 1, 2, 3]

Largest square side: 3
Area: 9

Time and Space Complexity

  • Time Complexity: O(m × n) where m and n are matrix dimensions
  • Space Complexity: O(1) as we modify the input matrix in-place

Conclusion

This dynamic programming approach efficiently finds the largest square of 1s by transforming each cell to store the maximum square size ending at that position. The algorithm runs in linear time and uses constant extra space.

Updated on: 2026-03-25T13:05:17+05:30

785 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements