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

โปรแกรมค้นหาค่าเป้าหมายในเมทริกซ์ใน Python

สมมติว่ามีเมทริกซ์ 2D ที่แต่ละแถวและคอลัมน์เรียงจากน้อยไปมาก ต้องการตรวจสอบว่ามีค่า target อยู่ในเมทริกซ์หรือไม่

ตัวอย่าง: เมทริกซ์ [[2,4,30],[3,4,31],[6,6,32]], target = 31 ผลลัพธ์ True

ขั้นตอนการแก้ปัญหา

  1. เริ่มจากมุมขวาบน: col = จำนวนคอลัมน์ - 1
  2. วนลูปแต่ละแถว i:
    • ขณะ matrix[i][col] > target และ col >= 0: col -= 1
    • ถ้า matrix[i][col] == target: คืน True
  3. คืน False

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

class Solution:
    def solve(self, matrix, target):
        col = len(matrix[0]) - 1
        for i in range(len(matrix)):
            while matrix[i][col] > target and col >= 0:
                col = col - 1
            if matrix[i][col] == target:
                return True
        return False

ob = Solution()
matrix = [[2, 4, 30], [3, 4, 31], [6, 6, 32]]
target = 31
print(ob.solve(matrix, target))

อินพุต

matrix = [[2, 4, 30], [3, 4, 31], [6, 6, 32]] target = 31

เอาต์พุต

True