Check if a matrix contains a square submatrix with 0 as boundary element | Java implementation of the above approach ; Function checks if square with all 0 's in boundary  exists in the matrix ; r1 is the top row , c1 is the left col r2 is the bottom row , c2 is the right ; Function checks if the boundary of the square consists of 0 's ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static int squareOfZeroes ( int [ ] [ ] matrix ) { int lastIdx = matrix . length - 1 ; Map < String , Boolean > cache = new HashMap < String , Boolean > ( ) ; return ( hasSquareOfZeroes ( matrix , 0 , 0 , lastIdx , lastIdx , cache ) ) ? 1 : 0 ; } static boolean hasSquareOfZeroes ( int [ ] [ ] matrix , int r1 , int c1 , int r2 , int c2 , Map < String , Boolean > cache ) { if ( r1 >= r2 c1 >= c2 ) return false ; String key = r1 + " - " + c1 + " - " + r2 + " - " + c2 ; if ( cache . containsKey ( key ) ) return cache . get ( key ) ; cache . put ( key , isSquareOfZeroes ( matrix , r1 , c1 , r2 , c2 ) || hasSquareOfZeroes ( matrix , r1 + 1 , c1 + 1 , r2 - 1 , c2 - 1 , cache ) || hasSquareOfZeroes ( matrix , r1 , c1 + 1 , r2 - 1 , c2 , cache ) || hasSquareOfZeroes ( matrix , r1 + 1 , c1 , r2 , c2 - 1 , cache ) || hasSquareOfZeroes ( matrix , r1 + 1 , c1 + 1 , r2 , c2 , cache ) || hasSquareOfZeroes ( matrix , r1 , c1 , r2 - 1 , c2 - 1 , cache ) ) ; return cache . get ( key ) ; } static boolean isSquareOfZeroes ( int [ ] [ ] matrix , int r1 , int c1 , int r2 , int c2 ) { for ( int row = r1 ; row < r2 + 1 ; row ++ ) { if ( matrix [ row ] [ c1 ] != 0 matrix [ row ] [ c2 ] != 0 ) return false ; } for ( int col = c1 ; col < c2 + 1 ; col ++ ) { if ( matrix [ r1 ] [ col ] != 0 matrix [ r2 ] [ col ] != 0 ) return false ; } return true ; } public static void main ( String [ ] args ) { int [ ] [ ] matrix = { { 1 , 1 , 1 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 0 , 1 } , { 0 , 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 0 , 1 , 0 , 1 } , { 0 , 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 , 0 , 1 } } ; int ans ; ans = squareOfZeroes ( matrix ) ; if ( ans == 1 ) { System . out . println ( " True " ) ; } else { System . out . println ( " False " ) ; } } }