Jump Game III in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of non-negative integers arr, we are initially positioned at start index of the array. When we are present at index i, we can jump to i + arr[i] or i - arr[i], check if we can reach to any index with value 0. We have to keep in mind that we cannot jump outside of the array at any time. So if the input is like: arr = [4,2,3,0,3,1,2] and start from 5, then output will be true, as move 5 -> 4 -> 1 -> 3, or 5 -> 6 -> 4 -> 1 -> 3.

To solve this, we will follow these steps −

  • n := size of arr
  • define a queue q, insert start into q, define a set called visited, and insert start into the set visited
  • while queue is not empty,
    • curr := front element of q, delete front element from q
    • if array[curr] is 0, then return true
    • if curr + arr[curr] < n and curr + arr[curr] is not present in visited set, then
      • insert curr + arr[curr] into q
      • insert curr + arr[curr] into visited
    • if curr - arr[curr] >= 0 and curr - arr[curr] is not present in visited set, then
      • insert curr - arr[curr] into q
      • insert curr - arr[curr] into visited
  • return false

Example

Let us see the following implementation to get better understanding −

class Solution {
   public:
   bool canReach(vector<int>& arr, int start) {
      int n = arr.size();
      queue <int> q;
      q.push(start);
      set <int> visited;
      visited.insert(start);
      while(!q.empty()){
         int curr = q.front();
         q.pop();
         if(arr[curr] == 0)return true;
         if(curr + arr[curr] < n && !visited.count(curr + arr[curr])){
            q.push(curr + arr[curr]);
            visited.insert(curr + arr[curr]);
         }
         if(curr - arr[curr] >= 0 && !visited.count(curr - arr[curr])){
            q.push(curr - arr[curr]);
            visited.insert(curr - arr[curr]);
         }
      }
      return false;
   }
};

Input

[4,2,3,0,3,1,2]
5

Output

true
raja
Published on 18-Mar-2020 05:38:41
Advertisements