Skip to content
Advertisement

Smallest Submatrix in python

It contains an R*C matrix with unique digits. I have to print the submatrix having minimum and maximum integer

Input:  

5 6
73 31 19 10 27 12
82 66 15 23 64 89
17 40 74 41 99 38
46 79 91 28 57 35
94 97 45 55 33 56

Output:

10 27
23 64
41 99

The minimum integer in the matrix is 10
The maximum integer in the matrix is 99

This is my code:

a,b=map(int,input().split())
m=[list(map(int,input().split())) for i in range(a)]

pv=min(map(min,m))
ak=max(map(max,m))

def find(e,mat):
    for i in range(len(mat)):
        for j in range(len(mat[i])):
            if mat[i][j]==e:
                return [i,j]

I need a solution without a NumPy array.

I found the max and min values and also their index. After that, I don’t know what to do.

Advertisement

Answer

You can iterate over matrix again and get only values in the interval from your found min and max coordinates.

a, b = map(int, input().split())
m = [list(map(int, input().split())) for i in range(a)]
print(m)
pv = min(map(min, m))
ak = max(map(max, m))


def find(e, mat):
    for i in range(len(mat)):
        for j in range(len(mat[i])):
            if mat[i][j] == e:
                return [i, j]


def find_matrix(min_cor, max_cor, mat):
    res = []
    min_i, min_j = min_cor
    max_i, max_j = max_cor
   #swap if max coordinates is before min 
    if(min_i > max_i):
        min_i,max_i = max_i, min_i

    if(min_j > max_j):
        min_j,max_j = max_j,min_j
    for i in range(len(mat)):
        cur_row = []
        for j in range(len(mat[i])):
            if min_i <= i <= max_i and min_j <= j <= max_j:
                cur_row.append(mat[i][j])
        if cur_row:
            res.append(cur_row)
    return res

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement