Jump Game III in C++


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 a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
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;
   }
};
main(){
   vector<int> v = {4,2,3,0,3,1,2};
   Solution ob;
   cout << (ob.canReach(v, 5));
}

Input

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

Output

1

Updated on: 30-Apr-2020

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements