มี Matrix mat1, mat2 ขนาด n x m ต้องเช็คว่า Swap Element ตำแหน่ง (i,j) ระหว่าง mat1, mat2 ได้ ทำให้ทั้งสอง Matrix Strictly Increasing (Row และ Column)
เช่น mat1 = [[7,15],[16,10]] mat2 = [[14,9],[8,17]] Output True Swap (7,14) และ (10,17) ได้ Matrices Increasing
ขั้นตอนแก้:
- แต่ละ Cell (i,j): ถ้า mat1[i][j] > mat2[i][j] Swap ให้ mat1 <= mat2
- เช็ค Row: mat1[i][j] < mat1[i][j+1] และ mat2[i][j] < mat2[i][j+1]
- เช็ค Column: mat1[i][j] < mat1[i+1][j] และ mat2[i][j] < mat2[i+1][j]
ตัวอย่างโค้ด
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