VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-square-matrices-with-all-1s/

⇱ Number of square matrices with all 1s - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of square matrices with all 1s

Last Updated : 12 Jul, 2025

Given an N*M matrix containing only 0s and 1s, the task is to count the number of square submatrices containing all 1s.

Examples:

Input: arr[][] = {{0, 1, 1, 1}, 
{1, 1, 1, 1}, 
{0, 1, 1, 1}} 
Output: 15 
Explanation:
There are 10 squares of side length 1. 
There are 4 squares of side length 2. 
There is 1 square of side length 3. 
Total number of squares = 10 + 4 + 1 = 15.

Input: arr[][] = {{1, 1}, 
{1, 1}, 
{1, 1}} 
Output: 8
There are 6 squares of length 1
There are 2 squares of length 2

Input: arr[][] = {{1, 0, 1}, 
{1, 1, 0}, 
{1, 1, 0}} 
Output:

Naive Recursion Approach:

  • At every position, we determine the maximum possible side length for a square if we consider that position as the top left corner.
  • Therefore, we can calculate the total number of squares as sum of these lengths

How do we compute total numbers of squares that have arr[i][j] as the top left.

  1. If arr[i][j] is 0, we return 0 and do not proceed.
  2. We initialize res = 0
  3. If arr[i][j] is 1, then we add 1 to the result.
  4. Now we recursively compute number of squares where right or arr[i][j+1], below or arr[i+1][j] and below-right or arr[i+1][j+1] are individually top left corners. And take take the minimum of these 3 and add to the result.

Output
7

Time Complexity: Exponential

Using Memoization:

There are overlapping subproblems as we make three calls for adjacent cells of every cell. So we can optimize the recursive solution. We make a 2D memo array to store the results of already computed subptoblems. We make it 2D because there are two parameters (i and j) that change in recursion. We make the size of memo as m x n because these parameters range from 0 to m-1 and 0 to n-1 respectively. We initialize the memo array as -1 to indiciate nothing is computed and before making a recursive call, we check if the value for the current position is already present in the memo.. If so, it directly returns that value instead of recomputing it.


Output
7

Time Complexity: O(m x n)
Auxiliary Space: O(1)

Using DP Buttom-Up:

This problem can be solved using Dynamic Programming.  

  1. Let the array dp[i][j] store the number of square matrices ending at (i, j)
  2. The recurrence relation to find the number of squares ending at (i, j) can be given by:
    • If dp[i][j] is 1:
      • dp[i][j] = min( min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1
    • Else if arr[i][j] is 0: 
      • dp[i][j] = 0
  3. Calculate the sum of the array which is equal to the number of square submatrices with all 1s.

Below is the implementation of the above approach:  


Output
7

Time Complexity: O(m x n)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: