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 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > matrixMinimum ( vector < vector < int > > nums , int K ) { int N = nums . size ( ) ; int M = nums [ 0 ] . size ( ) ; vector < vector < int > > res ( N - K + 1 , vector < int > ( M - K + 1 ) ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M - K + 1 ; j ++ ) { int mini = INT_MAX ; for ( int k = j ; k < j + K ; k ++ ) { mini = min ( mini , nums [ i ] [ k ] ) ; } nums [ i ] [ j ] = mini ; } } for ( int j = 0 ; j < M ; j ++ ) { for ( int i = 0 ; i < N - K + 1 ; i ++ ) { int mini = INT_MAX ; for ( int k = i ; k < i + K ; k ++ ) { mini = min ( mini , nums [ k ] [ j ] ) ; } nums [ i ] [ j ] = mini ; } } 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 ; } void smallestinKsubmatrices ( vector < vector < int > > arr , int K ) { vector < vector < int > > res = matrixMinimum ( arr , K ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { for ( int j = 0 ; j < res [ 0 ] . size ( ) ; j ++ ) { cout << res [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { vector < vector < 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 ) ; }