กำหนด Binary Matrix ขนาด m x n หาจำนวน Special Positions ใน Matrix ตำแหน่ง (i,j) เป็น Special เมื่อ mat[i][j] = 1 และสมาชิกอื่นใน Row i และ Column j ทั้งหมดเป็น 0
Input Matrix:
| 1 | 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 0 | 0 |
| 0 | 0 | 0 | 1 | 1 |
| 0 | 1 | 0 | 0 | 0 |
Output: 3 Special Positions: (0,0), (1,2), (3,1)
ขั้นตอนการแก้ปัญหา
- special := 0
- Loop i = 0 ถึง Row Count - 1: ถ้า จำนวน 1 ใน Row matrix[i] == 1:
- numOfOne := 0
- indexOfOne := ตำแหน่งของ 1 ใน matrix[i]
- Loop j = 0 ถึง Column Size - 1: ถ้า matrix[j][indexOfOne] == 1: numOfOne += 1
- ถ้า numOfOne > 1: Break Loop
- ถ้า numOfOne == 1: special += 1
- Return special
ตัวอย่าง Python
def solve(matrix):
special = 0
for i in range(len(matrix)):
if matrix[i].count(1) == 1:
numOfOne = 0
indexOfOne = matrix[i].index(1)
for j in range(len(matrix)):
if matrix[j][indexOfOne] == 1:
numOfOne += 1
if numOfOne > 1:
break
if numOfOne == 1:
special += 1
return special
matrix = [[1,0,0,0,0],
[0,0,1,0,0],
[0,0,0,1,1],
[0,1,0,0,0]]
print(solve(matrix))
Input
[[1,0,0,0,0], [0,0,1,0,0], [0,0,0,1,1], [0,1,0,0,0]]
Output
3