Post

1428 Jump Game Iii

1428 Jump Game Iii

Jump Game III image

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 can not jump outside of the array at any time.

 

Example 1:

1
2
3
4
5
6
7
8
**Input:** arr = [4,2,3,0,3,1,2], start = 5
**Output:** true
**Explanation:** 
All possible ways to reach at index 3 with value 0 are: 
index 5 -> index 4 -> index 1 -> index 3 
index 5 -> index 6 -> index 4 -> index 1 -> index 3 

Example 2:

1
2
3
4
5
6
7
**Input:** arr = [4,2,3,0,3,1,2], start = 0
**Output:** true 
Explanation: 
One possible way to reach at index 3 with value 0 is: 
index 0 -> index 4 -> index 1 -> index 3

Example 3:

1
2
3
4
5
**Input:** arr = [3,0,2,1,2], start = 2
**Output:** false
**Explanation: **There is no way to reach at index 1 with value 0.

 

Constraints:

1
2
3
1 <= arr.length <= 5 * 104
0 <= arr[i] < arr.length
0 <= start < arr.length
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

use std::collections::HashSet;

impl Solution {
    pub fn can_reach(arr: Vec<i32>, start: i32) -> bool {
        // simple dfs may work
        // memeory limit is exceeded, so a BFS should work better in this case 


        let mut num : Vec<i32> = Vec::new();
        num.push(start);
        let mut hs = HashSet::new();

        while(num.len() > 0) {
            let mut index =  num.pop().unwrap();
            if arr[index as usize] == 0 {
                return true;
            }
            hs.insert(index);
            let a = index - arr[index as usize];
            let b = index + arr[index as usize];
            if  a >= 0 && a < arr.len() as i32 && !hs.contains(&a){
                num.push(a);
            }

            if b >= 0 && b < arr.len() as i32 && !hs.contains(&b){
                num.push(b);
            }
            
        }
        return false;

        fn check(index : i32, arr : &Vec<i32>, mut mp : HashSet<i32>) -> bool {
            if index > arr.len() as i32 - 1 || index < 0 {
                return false;
            }

            if mp.contains(&index) {
                return false;
            }

            if arr[index as usize] == 0 {
                return true;
            }

            mp.insert(index);

            let mut a = check(index + arr[index as usize], arr, mp.clone());
            if a {
                return true;
            }

            a = check(index - arr[index as usize], arr, mp.clone());

            return a;

        }

       
        //return check(start, &arr, hs);
    }
}



This post is licensed under CC BY 4.0 by the author.