Number of square matrices with all 1s

26 Apr, 2021
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, 0, 1}, {1, 1, 0}, {1, 1, 0}} Output: 7 
Approach: This problem can be solved using Dynamic Programming.  
Let the array arr[i][j] store the number of square matrices ending at (i, j)The recurrence relation to find the number of squares ending at (i, j) can be given by:If arr[i][j] is 1:arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1Else if arr[i][j] is 0: arr[i][j] = 0Calculate the sum of the array which is equal to the number of square submatrices with all 1s.
Let the array arr[i][j] store the number of square matrices ending at (i, j)
The recurrence relation to find the number of squares ending at (i, j) can be given by:If arr[i][j] is 1:arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1Else if arr[i][j] is 0: arr[i][j] = 0
If arr[i][j] is 1:arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1
arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1
Else if arr[i][j] is 0: arr[i][j] = 0
arr[i][j] = 0
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:  
CPP
Java
Python
C#
Javascript
// C++ program to return the number of// square submatrices with all 1s#include <bits/stdc++.h>using namespace std; #define n 3#define m 3 // Function to return the number of// square submatrices with all 1sint countSquareMatrices(int a[][m],                        int N, int M){    // Initialize count variable    int count = 0;     for (int i = 1; i < N; i++) {        for (int j = 1; j < M; j++) {            // If a[i][j] is equal to 0            if (a[i][j] == 0)                continue;             // Calculate number of            // square submatrices            // ending at (i, j)            a[i][j] = min(min(a[i - 1][j],                              a[i][j - 1]),                          a[i - 1][j - 1])                      + 1;        }    }     // Calculate the sum of the array    for (int i = 0; i < N; i++)        for (int j = 0; j < M; j++)            count += a[i][j];     return count;} // Driver codeint main(){    int arr[][m] = { { 1, 0, 1 },                     { 1, 1, 0 },                     { 1, 1, 0 } };     cout << countSquareMatrices(arr, n, m);     return 0;}
// Java program to return the number of// square submatrices with all 1sclass GFG{         final static int n = 3;    final static int m = 3;         // Function to return the number of    // square submatrices with all 1s    static int countSquareMatrices(int a[][], int N, int M)    {        // Initialize count variable        int count = 0;             for (int i = 1; i < N; i++)        {            for (int j = 1; j < M; j++)            {                // If a[i][j] is equal to 0                if (a[i][j] == 0)                    continue;                     // Calculate number of                // square submatrices                // ending at (i, j)                a[i][j] = Math.min(Math.min(a[i - 1][j], a[i][j - 1]),                            a[i - 1][j - 1]) + 1;            }        }             // Calculate the sum of the array        for (int i = 0; i < N; i++)            for (int j = 0; j < M; j++)                count += a[i][j];             return count;    }         // Driver code    public static void main (String[] args)    {        int arr[][] = { { 1, 0, 1 },                        { 1, 1, 0 },                        { 1, 1, 0 } };             System.out.println(countSquareMatrices(arr, n, m));    }} // This code is contributed by AnkitRai01
# Python3 program to return the number of# square submatrices with all 1sn = 3m = 3 # Function to return the number of# square submatrices with all 1sdef countSquareMatrices(a, N, M):         # Initialize count variable    count = 0     for i in range(1, N):        for j in range(1, M):                         # If a[i][j] is equal to 0            if (a[i][j] == 0):                continue             # Calculate number of            # square submatrices            # ending at (i, j)            a[i][j] = min([a[i - 1][j],                      a[i][j - 1], a[i - 1][j - 1]])+1     # Calculate the sum of the array    for i in range(N):        for j in range(M):            count += a[i][j]     return count # Driver code arr = [ [ 1, 0, 1],    [ 1, 1, 0 ],    [ 1, 1, 0 ] ] print(countSquareMatrices(arr, n, m)) # This code is contributed by mohit kumar 29
// C# program to return the number of// square submatrices with all 1susing System; class GFG{         static int n = 3;    static int m = 3;         // Function to return the number of    // square submatrices with all 1s    static int countSquareMatrices(int [,]a, int N, int M)    {        // Initialize count variable        int count = 0;             for (int i = 1; i < N; i++)        {            for (int j = 1; j < M; j++)            {                // If a[i][j] is equal to 0                if (a[i, j] == 0)                    continue;                     // Calculate number of                // square submatrices                // ending at (i, j)                a[i, j] = Math.Min(Math.Min(a[i - 1, j], a[i, j - 1]),                            a[i - 1, j - 1]) + 1;            }        }             // Calculate the sum of the array        for (int i = 0; i < N; i++)            for (int j = 0; j < M; j++)                count += a[i, j];             return count;    }         // Driver code    public static void Main()    {        int [,]arr = { { 1, 0, 1 },                        { 1, 1, 0 },                        { 1, 1, 0 } };             Console.WriteLine(countSquareMatrices(arr, n, m));    }} // This code is contributed by AnkitRai01
<script> // Javascript program to return the number of// square submatrices with all 1s var n = 3var m = 3 // Function to return the number of// square submatrices with all 1sfunction countSquareMatrices(a, N, M){    // Initialize count variable    var count = 0;     for (var i = 1; i < N; i++) {        for (var j = 1; j < M; j++) {            // If a[i][j] is equal to 0            if (a[i][j] == 0)                continue;             // Calculate number of            // square submatrices            // ending at (i, j)            a[i][j] = Math.min(Math.min(a[i - 1][j],                              a[i][j - 1]),                          a[i - 1][j - 1])                      + 1;        }    }     // Calculate the sum of the array    for (var i = 0; i < N; i++)        for (var j = 0; j < M; j++)            count += a[i][j];     return count;} // Driver codevar arr = [ [ 1, 0, 1 ],                 [ 1, 1, 0 ],                 [ 1, 1, 0 ] ];document.write( countSquareMatrices(arr, n, m)); </script>
Output : 
7
Time Complexity: O(N*M)Auxiliary Space: O(1)
mohit kumar 29
ankthon
subhammahato348
rutvik_56
Dynamic Programming
Matrix
Dynamic Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in an undirected graph
Count number of binary strings without consecutive 1's
Find if a string is interleaved of two other strings | DP-33
Optimal Substructure Property in Dynamic Programming | DP-2
Maximum sum such that no two elements are adjacent
Print a given matrix in spiral form
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem