Smallest element from all square submatrices of size K from a given Matrix | Java Program for the above approach ; Function to returns a smallest elements of all KxK submatrices of a given NxM matrix ; Stores the dimensions of the given matrix ; Stores the required smallest elements ; Update the smallest elements row - wise ; Update the minimum column - wise ; Store the final submatrix with required minimum values ; Return the resultant matrix ; Function Call ; Print resultant matrix with the minimum values of KxK sub - matrix ; Driver Code ; Given matrix ; Given K
import java . util . * ; import java . lang . * ; class GFG { public static int [ ] [ ] matrixMinimum ( int [ ] [ ] nums , int K ) { int N = nums . length ; int M = nums [ 0 ] . length ; int [ ] [ ] res = new int [ N - K + 1 ] [ M - K + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M - K + 1 ; j ++ ) { int min = Integer . MAX_VALUE ; for ( int k = j ; k < j + K ; k ++ ) { min = Math . min ( min , nums [ i ] [ k ] ) ; } nums [ i ] [ j ] = min ; } } for ( int j = 0 ; j < M ; j ++ ) { for ( int i = 0 ; i < N - K + 1 ; i ++ ) { int min = Integer . MAX_VALUE ; for ( int k = i ; k < i + K ; k ++ ) { min = Math . min ( min , nums [ k ] [ j ] ) ; } nums [ i ] [ j ] = min ; } } for ( int i = 0 ; i < N - K + 1 ; i ++ ) for ( int j = 0 ; j < M - K + 1 ; j ++ ) res [ i ] [ j ] = nums [ i ] [ j ] ; return res ; } public static void smallestinKsubmatrices ( int arr [ ] [ ] , int K ) { int [ ] [ ] res = matrixMinimum ( arr , K ) ; for ( int i = 0 ; i < res . length ; i ++ ) { for ( int j = 0 ; j < res [ 0 ] . length ; j ++ ) { System . out . print ( res [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { - 1 , 5 , 4 , 1 , - 3 } , { 4 , 3 , 1 , 1 , 6 } , { 2 , - 2 , 5 , 3 , 1 } , { 8 , 5 , 1 , 9 , - 4 } , { 12 , 3 , 5 , 8 , 1 } } ; int K = 3 ; smallestinKsubmatrices ( arr , K ) ; } }