AlgoMaster Logo

Count Square Submatrices with All Ones

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Solution

Intuition:

The basic idea is to count all possible square submatrices in the matrix that have all ones. The brute force approach involves iterating over every potential square submatrix and checking if it consists entirely of ones.

  • Start at every element in the matrix, try expanding it into a square submatrix.
  • Check each submatrix to see if every entry is 1.
  • If a square is valid, increase the count.

This approach checks every possible square matrix, and hence can be quite inefficient for larger matrices.

Code:

2. Dynamic Programming

Intuition:

The dynamic programming approach incrementally builds a solution using previous results. The key insight is recognizing that the size of the square submatrix ending at position (i, j) can be determined by the smallest square ending at positions (i-1, j)(i, j-1), and (i-1, j-1), if (i, j) itself is 1.

  • Create a DP table where dp[i][j] represents the size of the largest square submatrix with all ones ending at (i, j).
  • Update this table iteratively based on the above relation.
  • Sum up all the entries in the DP table to get the total count of squares.

Code: