Smallest element from all square submatrices of size K from a given Matrix | 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 ; Given matrix ; Given K
function matrixMinimum ( nums , K ) { let N = nums . length ; let M = nums [ 0 ] . length ; let res = new Array ( N - K + 1 ) ; for ( var i = 0 ; i < res . length ; i ++ ) { res [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < M - K + 1 ; j ++ ) { let min = Number . MAX_VALUE ; for ( let k = j ; k < j + K ; k ++ ) { min = Math . min ( min , nums [ i ] [ k ] ) ; } nums [ i ] [ j ] = min ; } } for ( let j = 0 ; j < M ; j ++ ) { for ( let i = 0 ; i < N - K + 1 ; i ++ ) { let min = Number . MAX_VALUE ; for ( let k = i ; k < i + K ; k ++ ) { min = Math . min ( min , nums [ k ] [ j ] ) ; } nums [ i ] [ j ] = min ; } } for ( let i = 0 ; i < N - K + 1 ; i ++ ) for ( let j = 0 ; j < M - K + 1 ; j ++ ) res [ i ] [ j ] = nums [ i ] [ j ] ; return res ; } function smallestinKsubmatrices ( arr , K ) { let res = matrixMinimum ( arr , K ) ; for ( let i = 0 ; i < res . length ; i ++ ) { for ( let j = 0 ; j < res [ 0 ] . length ; j ++ ) { document . write ( res [ i ] [ j ] + " " ) ; } document . write ( " " ) ; } } let 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 ] ] ; let K = 3 ; smallestinKsubmatrices ( arr , K ) ;