Smallest element from all square submatrices of size K from a given Matrix | C # 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 readonly 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
using System ; class GFG { public static int [ , ] matrixMinimum ( int [ , ] nums , int K ) { int N = nums . GetLength ( 0 ) ; int M = nums . GetLength ( 1 ) ; 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 = int . MaxValue ; 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 = int . MaxValue ; 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 . GetLength ( 0 ) ; i ++ ) { for ( int j = 0 ; j < res . GetLength ( 1 ) ; j ++ ) { Console . Write ( res [ i , j ] + " ▁ " ) ; } Console . WriteLine ( ) ; } } 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 ) ; } }