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

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

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

 7 15 16 10

 14 9 8 17

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

 14 15 16 17

 7 9 8 10

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 13:17:14