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

โปรแกรมนับสมาชิกเมทริกซ์ที่ตรงเงื่อนไข Row/Column ใน Python

ให้ Binary Matrix หาจำนวนเซลล์ที่:

  1. matrix[r][c] == 1
  2. Row r มี 1 เพียงตัวเดียว (ที่คอลัมน์ c)
  3. Column c มี 1 เพียงตัวเดียว (ที่แถว r)

ตัวอย่าง: [[0,0,1],[1,0,0],[0,1,0]] → 3 (ตำแหน่ง (0,2), (1,0), (2,1))

ขั้นตอน (O(m×n))

  1. คำนวณ row[r] = sum(matrix[r]) และ col[c] = sum(matrix[*][c])
  2. วนทุกเซลล์ ถ้า matrix[r][c]==1 and row[r]==1 and col[c]==1 → นับ +1

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

def solve(matrix):
    if not matrix:
        return 0
    row = [sum(r) for r in matrix]
    col = [sum(c) for c in zip(*matrix)]
    m, n = len(matrix), len(matrix[0])
    res = 0
    for r in range(m):
        for c in range(n):
            if matrix[r][c] == 1 and row[r] == 1 and col[c] == 1:
                res += 1
    return res

matrix = [[0,0,1],[1,0,0],[0,1,0]]
print(solve(matrix))  # Output: 3

อินพุต

[[0, 0, 1],[1, 0, 0],[0, 1, 0]]

เอาต์พุต

3