สมมติว่าเรามีเมทริกซ์สี่เหลี่ยมจัตุรัสขนาด m x m เราต้องการค้นหาองค์ประกอบที่แตกต่างกันทั้งหมดที่ปรากฏในทุกแถวของเมทริกซ์ที่กำหนด
เช่น หากอินพุตเป็นดังนี้:
| 13 | 2 | 15 | 4 | 17 |
| 15 | 3 | 2 | 4 | 36 |
| 15 | 2 | 15 | 4 | 12 |
| 15 | 26 | 4 | 3 | 2 |
| 2 | 19 | 4 | 22 | 15 |
ผลลัพธ์จะเป็น [2, 4, 15]
ขั้นตอนการแก้ปัญหา
- สร้างฟังก์ชัน
sortRows()ที่รับเมทริกซ์เข้ามา - นับจำนวนแถว
n - ทำการเรียงลำดับแต่ละแถวในเมทริกซ์
- ในฟังก์ชันหลัก:
- สร้างรายการ
current_idxขนาด n เติมค่า 0 - ตั้งค่า
f = 0 - วนลูป while
current_idx[0] < n:- เก็บค่า
value = matrix[0][current_idx[0]] - ตั้งค่า
present = True - ตรวจสอบแถวที่ 1 ถึง n-1 ว่ามีค่า
valueหรือไม่ โดยเลื่อดัชนีในแต่ละแถว - หากไม่พบในแถวไหน ให้ตั้ง
present = False - หากดัชนีใดถึงปลายแถว ให้ตั้ง
f = 1และออกจากลูป - หาก
presentเป็นจริง ให้แสดงค่าvalue - เพิ่ม
current_idx[0]
- เก็บค่า
- สร้างรายการ
ตัวอย่างโค้ด Python
def sortRows(matrix):
n = len(matrix)
for i in range(n):
matrix[i].sort()
def find_common(matrix):
n = len(matrix)
sortRows(matrix)
current_idx = [0] * n
f = 0
while current_idx[0] < n:
value = matrix[0][current_idx[0]]
present = True
for i in range(1, n):
while current_idx[i] < n and matrix[i][current_idx[i]] <= value:
current_idx[i] += 1
if matrix[i][current_idx[i] - 1] != value:
present = False
if current_idx[i] == n:
f = 1
break
if present:
print(value, end=", ")
if f == 1:
break
current_idx[0] += 1
mat = [
[13, 2, 15, 4, 17],
[15, 3, 2, 4, 36],
[15, 2, 15, 4, 12],
[15, 26, 4, 3, 2],
[2, 19, 4, 22, 15]
]
find_common(mat)
อินพุต
[[13, 2, 15, 4, 17], [15, 3, 2, 4, 36], [15, 2, 15, 4, 12], [15, 26, 4, 3, 2], [2, 19, 4, 22, 15]]
เอาต์พุต
2, 4, 15,