# Check if matrix can be converted to another matrix by transposing square sub-matrices in Python

Suppose we have two N X M called mat1 and mat2. In an operation, we can transpose any square sub-matrix in mat1. We have to check whether we can get mat2 from mat1 or not by performing given operation.

So, if the input is like

 5 6 7 1 2 3 6 8 9

 5 6 2 1 7 3 6 8 9

then the output will be True, because if we get transpose of top right sub-matrix of size 2x2 of mat1, we will get mat2.

To solve this, we will follow these steps −

• row := row count of matrices
• column := column count of matrices
• for i in range 0 to row - 1, do
• temp1 := a new list, temp2 := a new list
• r := i, col := 0
• while r >= 0 and col < column, do
• insert mat1[r, col] into temp1
• insert mat2[r, col] into temp2
• r := r - 1, col := col + 1
• sort the list temp1 and temp2
• for i in range 0 to size of temp1 - 1, do
• if temp1[i] is not same as temp2[i], then
• return False
• for j in range 1 to column - 1, do
• temp1 := a new list, temp2 := a new list
• r := row - 1, col := j
• while r >= 0 and col < column, do
• insert mat1[r, col] into temp1
• insert mat2[r, col] into temp2
• r := r - 1, col := col + 1
• sort the list temp1 and temp2
• for i in range 0 to size of temp1 - 1, do
• if temp1[i] is not same as temp2[i], 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)
column = len(mat1[0])
for i in range(row):
temp1 = []
temp2 = []
r = i
col = 0
while r >= 0 and col < column:
temp1.append(mat1[r][col])
temp2.append(mat2[r][col])
r -= 1
col += 1
temp1.sort()
temp2.sort()
for i in range(len(temp1)):
if temp1[i] != temp2[i]:
return False
for j in range(1, column):
temp1 = []
temp2 = []
r = row - 1
col = j
while r >= 0 and col < column:
temp1.append(mat1[r][col])
temp2.append(mat2[r][col])
r -= 1
col += 1
temp1.sort()
temp2.sort()
for i in range(len(temp1)):
if temp1[i] != temp2[i]:
return False
return True
mat1 = [
[5, 6, 7],
[1, 2, 3],
[6, 8, 9]]
mat2 = [
[5, 6, 2],
[1, 7, 3],
[6, 8, 9]]
print(solve(mat1, mat2))

## Input

[
[5, 6, 7],
[1, 2, 3],
[6, 8, 9]],
[
[5, 6, 2],
[1, 7, 3],
[6, 8, 9]]

## Output

True