Check if it is possible to make two matrices strictly increasing by swapping corresponding values only in Python


Suppose we have two matrices of size n x m named mat1 and mat2. We have to check where these two matrices are strictly increasing or not by swapping only two elements in different matrices only when they are at position (i, j) in both matrices.

So, if the input is like

71
5
1
6
1
0


1
4
9
81
7

then the output will be True as we can swap (7, 14) and (10, 17) pairs to make them strictly increasing.

1
4
1
5
1
6
1
7


79
81
0

To solve this, we will follow these steps −

  • row := row count of mat1
  • col := column count of mat1
  • for i in range 0 to row - 1, do
    • for j in range 0 to col - 1, do
      • if mat1[i,j] > mat2[i,j], then
        • swap mat1[i, j] and mat2[i, j]
    • for i in range 0 to row - 1, do
      • for j in range 0 to col-2, do
        • if mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], then
          • return False
    • for i in range 0 to row-2, do
      • for j in range 0 to col - 1, do
        • if mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], then
          • return False
  • return True

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(mat1, mat2):
   row = len(mat1)
   col = len(mat1[0])
   for i in range(row):
      for j in range(col):
         if mat1[i][j] > mat2[i][j]:
            mat1[i][j], mat2[i][j]= mat2[i][j], mat1[i][j]
   for i in range(row):
      for j in range(col-1):
         if mat1[i][j]>= mat1[i][j + 1] or mat2[i][j]>= mat2[i][j + 1]:
            return False
   for i in range(row-1):
      for j in range(col):
         if mat1[i][j]>= mat1[i + 1][j] or mat2[i][j]>= mat2[i + 1][j]:
            return False
   return True
mat1 = [[7, 15],
         [16, 10]]
mat2 = [[14, 9],
         [8, 17]]
print(solve(mat1, mat2))

Input

[[7, 15],
[16, 10]],
[[14, 9],
[8, 17]]

Output

True

Updated on: 18-Jan-2021

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements