41 lines
1.6 KiB
C++
Raw Normal View History

/**
* @file
* \brief Implementation of an algorithm to solve the jumping game problem
* \details
* This algorithm is a greedy algorithm.
* This solution takes in input as a vector and output as a boolean to check if you can reach the last position.
* @author rakshaa2000
*/
//Jump Game:
/*Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.*/
2020-09-01 00:08:54 +05:30
#include <vector>
#include<iostream>
2020-09-01 00:15:34 +05:30
//Implements the algorithm
/*We name the indices good and bad based on whether we can reach the destination if we start at that position.
*We initialize the last index as lastPos.
*Here, we start from the end of the array and check if we can ever reach the first index.
*We check if the sum of the index and the maximum jump count given is greater than or equal to the lastPos.
*If yes, then that is the last position you can reach starting from the back.
*After the end of the loop, if we reach the lastPos as 0, then the destination can be reached from the start position.
*/
2020-09-01 00:18:51 +05:30
bool canJump(std::vector<int> nums) {
2020-09-01 00:15:34 +05:30
auto lastPos = nums.size() - 1;
2020-09-01 00:12:43 +05:30
for (auto i = nums.size() - 1; i >= 0; i--) {
if (i + nums[i] >= lastPos) {
lastPos = i;
}
}
return lastPos == 0;
}
2020-09-01 00:18:51 +05:30
int main(){
//Sample test case
2020-09-01 00:18:51 +05:30
std::vector<int> num={4,3,1,0,5};
2020-09-01 00:22:20 +05:30
std::cout<<canJump(num); //Should display true, as when you take one step from position 0, you reach position 1, from which 3 steps lead you to the destination
2020-09-01 00:18:51 +05:30
return 0;
}