Skip to content

Commit 9d010df

Browse files
Merge pull request #2168 from Rey-han-24/main
feat: implement BFS solution for Jump Game III (#1306)
2 parents 36438f8 + 8a03353 commit 9d010df

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
def canReach(arr: list[int], start: int) -> bool:
2+
# 1. Initialize the queue with our starting position
3+
queue = [start]
4+
# 2. Keep track of visited indices so we don't get stuck in a loop
5+
visited = set()
6+
7+
while queue:
8+
# Get the current position
9+
curr = queue.pop(0)
10+
11+
# SUCCESS: We found a zero!
12+
if arr[curr] == 0:
13+
return True
14+
15+
# Mark current as visited
16+
visited.add(curr)
17+
18+
# Calculate possible jumps
19+
for next_pos in [curr + arr[curr], curr - arr[curr]]:
20+
# Check if the jump is within the array bounds and not visited
21+
if 0 <= next_pos < len(arr) and next_pos not in visited:
22+
queue.append(next_pos)
23+
24+
# If the queue is empty and we never hit 0, it's impossible
25+
return False
26+
27+
# --- Test Cases ---
28+
if __name__ == "__main__":
29+
# Test 1: Should be True (can reach index 5 or 6)
30+
print(f"Test 1: {canReach([4,2,3,0,3,1,2], 5)}")
31+
32+
# Test 2: Should be True (start is already 0)
33+
print(f"Test 2: {canReach([4,2,3,0,3,1,2], 0)}")
34+
35+
# Test 3: Should be False (cannot reach 0)
36+
print(f"Test 3: {canReach([3,0,2,1,2], 2)}")

0 commit comments

Comments
 (0)