Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
|
Jumping Game algorithm implementation More...
#include <cassert>
#include <iostream>
#include <vector>
Namespaces | |
namespace | greedy_algorithms |
for std::vector | |
Functions | |
bool | greedy_algorithms::can_jump (const std::vector< int > &nums) |
Checks whether the given element (default is 1 ) can jump to the last index. | |
static void | test () |
Function to test the above algorithm. | |
int | main () |
Main function. | |
Jumping Game algorithm implementation
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. This solution takes in input as a vector and output as a boolean to check if you can reach the last position. 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.
int main | ( | void | ) |
|
static |
Function to test the above algorithm.