Number of square matrices with all 1 s | Java program to return the number of square submatrices with all 1 s ; Function to return the number of square submatrices with all 1 s ; Initialize count variable ; If a [ i ] [ j ] is equal to 0 ; Calculate number of square submatrices ending at ( i , j ) ; Calculate the sum of the array ; Driver code
class GFG { final static int n = 3 ; final static int m = 3 ; static int countSquareMatrices ( int a [ ] [ ] , int N , int M ) { int count = 0 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j < M ; j ++ ) { if ( a [ i ] [ j ] == 0 ) continue ; a [ i ] [ j ] = Math . min ( Math . min ( a [ i - 1 ] [ j ] , a [ i ] [ j - 1 ] ) , a [ i - 1 ] [ j - 1 ] ) + 1 ; } } for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) count += a [ i ] [ j ] ; return count ; } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 1 , 0 , 1 } , { 1 , 1 , 0 } , { 1 , 1 , 0 } } ; System . out . println ( countSquareMatrices ( arr , n , m ) ) ; } }