1306. Jump Game III

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 to any index with value 0.

Notice that you can not jump outside of the array at any time.

 

Example 1:

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:

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:

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 <= arr.length <= 5 * 104
  • 0 <= arr[i] < arr.length
  • 0 <= start < arr.length

Rust Solution

struct Solution;
use std::collections::VecDeque;

impl Solution {
    fn can_reach(arr: Vec<i32>, start: i32) -> bool {
        let n = arr.len();
        let mut visited = vec![false; n];
        let mut queue = VecDeque::new();
        queue.push_back(start);
        visited[start as usize] = true;
        while let Some(i) = queue.pop_front() {
            if arr[i as usize] == 0 {
                return true;
            } else {
                let l = i - arr[i as usize];
                let r = i + arr[i as usize];
                if l >= 0 && !visited[l as usize] {
                    visited[l as usize] = true;
                    queue.push_back(l);
                }
                if r < n as i32 && !visited[r as usize] {
                    visited[r as usize] = true;
                    queue.push_back(r);
                }
            }
        }
        false
    }
}

#[test]
fn test() {
    let arr = vec![4, 2, 3, 0, 3, 1, 2];
    let start = 5;
    let res = true;
    assert_eq!(Solution::can_reach(arr, start), res);
    let arr = vec![4, 2, 3, 0, 3, 1, 2];
    let start = 0;
    let res = true;
    assert_eq!(Solution::can_reach(arr, start), res);
    let arr = vec![3, 0, 2, 1, 2];
    let start = 2;
    let res = false;
    assert_eq!(Solution::can_reach(arr, start), res);
}

Having problems with this solution? Click here to submit an issue on github.