Smallest element from all square submatrices of size K from a given Matrix | Python3 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 ; Given matrix ; Given K
import sys NEW_LINE def matrixMinimum ( nums , K ) : NEW_LINE INDENT N = len ( nums ) NEW_LINE M = len ( nums [ 0 ] ) NEW_LINE res = [ [ 0 for x in range ( M - K + 1 ) ] for y in range ( N - K + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M - K + 1 ) : NEW_LINE INDENT mn = sys . maxsize NEW_LINE for k in range ( j , j + K ) : NEW_LINE INDENT mn = min ( mn , nums [ i ] [ k ] ) NEW_LINE DEDENT nums [ i ] [ j ] = mn NEW_LINE DEDENT DEDENT for j in range ( M ) : NEW_LINE INDENT for i in range ( N - K + 1 ) : NEW_LINE INDENT mn = sys . maxsize NEW_LINE for k in range ( i , i + K ) : NEW_LINE INDENT mn = min ( mn , nums [ k ] [ j ] ) NEW_LINE DEDENT nums [ i ] [ j ] = mn NEW_LINE DEDENT DEDENT for i in range ( N - K + 1 ) : NEW_LINE INDENT for j in range ( M - K + 1 ) : NEW_LINE INDENT res [ i ] [ j ] = nums [ i ] [ j ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def smallestinKsubmatrices ( arr , K ) : NEW_LINE INDENT res = matrixMinimum ( arr , K ) NEW_LINE for i in range ( len ( res ) ) : NEW_LINE INDENT for j in range ( len ( res [ 0 ] ) ) : NEW_LINE INDENT print ( res [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT 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 ] ] NEW_LINE K = 3 NEW_LINE smallestinKsubmatrices ( arr , K ) NEW_LINE