สมมติว่าเรามีรายการตัวเลขเรียงลำดับ stones แสดงตำแหน่งหินในแม่น้ำ ต้องข้ามไปหินสุดท้าย ในแต่ละขั้นตอน กระโดดได้ k-1, k, k+1 หน่วย โดย k คือระยะกระโดดครั้งก่อน ตรวจสอบว่าข้ามได้หรือไม่
เช่น stones = [0, 1, 3, 4, 5, 6, 8, 9, 13] ผลลัพธ์ = True เส้นทาง: 0→1 (1), 1→3 (2), 3→5 (2), 5→8 (3), 8→13 (5)
ขั้นตอนการแก้ปัญหา (DFS + Memoization)
start := stones[0], end := stones[-1]stones_set := set(stones)- ฟังก์ชัน
check(pos=start, prev=0):- ถ้า
pos == endคืนTrue - วน
jump in [prev-1, prev, prev+1]:- ถ้า
jump >= 1:next_pos = pos + jump- ถ้า
next_pos in stones_setและcheck(next_pos, jump)คืนTrue
- ถ้า
- คืน
False
- ถ้า
- คืน
check()
ตัวอย่างโค้ด
class Solution:
def solve(self, A):
start, end = A[0], A[-1]
A = set(A)
def check(pos=start, prev=0):
if pos == end:
return True
for jump in [prev - 1, prev, prev + 1]:
if jump >= 1:
next_pos = jump + pos
if next_pos in A and check(next_pos, jump):
return True
return False
return check()
ob = Solution()
stones = [0, 1, 3, 4, 5, 6, 8, 9, 13]
print(ob.solve(stones))
ข้อมูลนำเข้า
[0, 1, 3, 4, 5, 6, 8, 9, 13]
ผลลัพธ์
True