สมมติว่าเรามี n คน แทนด้วยตัวเลข 0 ถึง n-1 และลิสต์ friends ที่แต่ละคู่ [a, b] แสดงว่า a และ b เป็นเพื่อน ตรวจสอบว่าทุกคนมีเพื่อนอย่างน้อย 1 คนหรือไม่
ตัวอย่าง: n = 3, friends = [[0, 1], [1, 2]] ผลลัพธ์ True
ขั้นตอนการแก้ปัญหา
- สร้างลิสต์
peopleขนาดnเติม 0 - สำหรับแต่ละ
linkในfriends:people[link[0]] = Truepeople[link[1]] = True
- ถ้ามี
personในpeopleที่เป็น False คืนค่าFalse - คืนค่า
True
ตัวอย่างโค้ด Python
class Solution:
def solve(self, n, friends):
people = [0 for i in range(n)]
for link in friends:
people[link[0]] = True
people[link[1]] = True
for person in people:
if not person:
return False
return True
ob = Solution()
n = 3
friends = [[0, 1], [1, 2]]
print(ob.solve(n, friends)) # Output: True
อินพุต / เอาต์พุต
Input: 3, [[0, 1], [1, 2]]
Output: True