
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Two Matrices Can Be Made Strictly Increasing 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
7 | 1 5 |
1 6 |
1 0 |
1 4 |
9 |
8 | 1 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 |
7 | 9 |
8 | 1 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]
- if mat1[i,j] > mat2[i,j], then
- 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
- if mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], then
- for j in range 0 to col-2, do
- 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
- if mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], then
- for j in range 0 to col - 1, do
- for j in range 0 to col - 1, do
- return True
Example
Let us see the following implementation to get better understanding −
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
Advertisements