Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบว่า Matrix คงที่หลัง Row Reversal หรือไม่ด้วย Python


สมมติมี Square Matrix ต้องตรวจสอบว่าหาก Reverse ทุก Row แล้ว Matrix เหมือนเดิมหรือไม่

เช่น Matrix 3x3:
[[6,8,6],
[2,8,2],
[3,3,3]]
Output True

ขั้นตอนแก้:

  • n = จำนวน Row
  • แต่ละ Row: left=0, right=n-1; While left<=right: ถ้า matrix[i][left] != matrix[i][right] Return False; left++, right--
  • Return True

ตัวอย่างโค้ด

def solve(matrix):
    n = len(matrix)
    for i in range(n):
        left = 0
        right = n - 1
        while left <= right:
            if matrix[i][left] != matrix[i][right]:
                return False
            left += 1
            right -= 1
    return True

matrix = [
    [6,8,6],
    [2,8,2],
    [3,3,3]]
print(solve(matrix))

Input

[[6,8,6], [2,8,2], [3,3,3]]

Output

True