commit 1e97b7b30898eac5636dbb9db2b1922c1e8de8ab
parent 402ade51c13c7265d53d843bbfb58e5c38c648ef
Author: Jack Sangdahl <jack@pngu.org>
Date: Sun, 17 May 2026 09:45:03 +0300
1306. jump game 3
Diffstat:
2 files changed, 64 insertions(+), 0 deletions(-)
diff --git a/jump_game3.c b/jump_game3.c
@@ -0,0 +1,31 @@
+// 1306. Jump Game III
+#include "leetcode.h"
+
+/*
+ * given an array of non-negative integers 'arr', you are initially positioned
+ * at 'start' index of the array. when you are at index 'i', you can jump to 'i
+ * + arr[i]' or 'i - arr[i]', check if you can reach any index with value 0.
+ * notice that you cannot jump outside of the array at any time.
+ */
+
+bool canReach(int *arr, int arrSize, int start) {
+ return 0 <= start && start < arrSize && arr[start] >= 0 &&
+ (!(arr[start] = -arr[start]) ||
+ canReach(arr, arrSize, start + arr[start]) ||
+ canReach(arr, arrSize, start - arr[start]));
+}
+
+int main() {
+ int a1[] = {4, 2, 3, 0, 3, 1, 2};
+ int a2[] = {4, 2, 3, 0, 3, 1, 2};
+ int a3[] = {3, 0, 2, 1, 2};
+ bool r1 = canReach(a1, ARRAY_SIZE(a1), 5);
+ bool r2 = canReach(a2, ARRAY_SIZE(a2), 0);
+ bool r3 = canReach(a3, ARRAY_SIZE(a3), 2);
+ printf("%d\n", r1);
+ assert(r1 == true);
+ printf("%d\n", r2);
+ assert(r2 == true);
+ printf("%d\n", r3);
+ assert(r3 == false);
+}
diff --git a/jump_game3.py b/jump_game3.py
@@ -0,0 +1,33 @@
+# 1306. Jump Game III
+from collections import deque
+
+"""
+given an array of non-negative integers 'arr', you are initially positioned
+at 'start' index of the array. when you are at index 'i', you can jump to 'i
++ arr[i]' or 'i - arr[i]', check if you can reach any index with value 0.
+notice that you cannot jump outside of the array at any time.
+"""
+
+
+class Solution:
+ def canReach(self, arr: List[int], start: int) -> bool:
+ q = deque([start])
+ while q:
+ start = q.popleft()
+ if arr[start] == 0:
+ return True
+ if arr[start] < 0:
+ continue
+ if start + arr[start] < len(arr):
+ q.append(start + arr[start])
+ if start - arr[start] >= 0:
+ q.append(start - arr[start])
+ arr[start] = -arr[start]
+ return False
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.canReach(arr=[4, 2, 3, 0, 3, 1, 2], start=5))
+ print(obj.canReach(arr=[4, 2, 3, 0, 3, 1, 2], start=0))
+ print(obj.canReach(arr=[3, 0, 2, 1, 2], start=2))