# Program to Find Out the Minimal Submatrices in Python

Suppose we have a 2D matrix and another value k. Our goal is to return a matrix that contains the lowest values of all k x k sub-matrices.

So, if the input is like

 3 5 6 8 6 5 4 3 12

and k =2,

then the output will be [[3, 5], [3, 3]] .

From the input, we can see that the top left submatrix has the lowest value of 3

3 5
8 6

The top right submatrix has the lowest value of 5

5 6
6 5

The bottom left submatrix has the lowest value of 3

8 6
4 3

The bottom right submatrix has the lowest value of 3

6 5
3 12

To solve this, we will follow these steps −

• for each r, row in index r and item row in matrix, do

• q := a new double ended queue

• nrow := a new list

• for i in range 0 to size of row, do

• if q and q[0] is same as i - k, then

• pop leftmost item of q

• while q and row[q[-1]] > row[i] is non-zero, do

• pop rightmost item of q

• insert i at the right end of q

• insert row[q[0]] at the end of nrow

• matrix[r] := nrow

• for j in range 0 to size of matrix[0], do

• q := a new double ended queue

• ncol := a new list

• for i in range 0 to size of matrix, do

• if q and q[0] is same as i - k, then

• pop leftmost item of q

• while q and matrix[q[-1]][j] > matrix[i][j] is non-zero, do

• pop rightmost item of q

• insert i at the right end of q

• insert matrix[q[0],j] at the right end of ncol

• for i in range 0 to size of matrix, do

• matrix[i, j] := ncol[i]

• ret := a new list of the size of matrix - k + 1 initialized with 0

• for i in range 0 to size of ret, do

• for j in range 0 to size of ret[0], do

• ret[i, j] := matrix[i + k - 1, j + k - 1]

• return ret

## Example

Let us see the following implementation to get a better understanding −

Live Demo

import collections
class Solution:
def solve(self, matrix, k):
for r, row in enumerate(matrix):
q = collections.deque()
nrow = []
for i in range(len(row)):
if q and q[0] == i - k:
q.popleft()
while q and row[q[-1]] > row[i]:
q.pop()
q.append(i)
nrow.append(row[q[0]])
matrix[r] = nrow
for j in range(len(matrix[0])):
q = collections.deque()
ncol = []
for i in range(len(matrix)):
if q and q[0] == i - k:
q.popleft()
while q and matrix[q[-1]][j] > matrix[i][j]:
q.pop()
q.append(i)
ncol.append(matrix[q[0]][j])
for i in range(len(matrix)):
matrix[i][j] = ncol[i]
ret = [[0] * (len(matrix[0]) - k + 1) for _ in range(len(matrix) - k + 1)]
for i in range(len(ret)):
for j in range(len(ret[0])):
ret[i][j] = matrix[i + k - 1][j + k - 1]
return ret
ob = Solution()
print(ob.solve(matrix = [
[3, 5, 6],
[8, 6, 5],
[4, 3, 12]
], k = 2))

## Input

[[3, 5, 6],[8, 6, 5],[4, 3, 12]], 2

## Output

[[3, 5], [3, 3]]

Updated on: 23-Dec-2020

183 Views