TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
jump_game.cpp
Go to the documentation of this file.
1
25#include <cassert>
26#include <iostream>
27#include <vector>
28
33namespace greedy_algorithms {
42bool can_jump(const std::vector<int> &nums) {
43 size_t lastPos = nums.size() - 1;
44 for (size_t i = lastPos; i != static_cast<size_t>(-1); i--) {
45 if (i + nums[i] >= lastPos) {
46 lastPos = i;
47 }
48 }
49 return lastPos == 0;
50}
51} // namespace greedy_algorithms
52
57static void test() {
58 assert(greedy_algorithms::can_jump(std::vector<int>({4, 3, 1, 0, 5})));
59 assert(!greedy_algorithms::can_jump(std::vector<int>({3, 2, 1, 0, 4})));
60 assert(greedy_algorithms::can_jump(std::vector<int>({5, 9, 4, 7, 15, 3})));
61 assert(!greedy_algorithms::can_jump(std::vector<int>({1, 0, 5, 8, 12})));
62 assert(greedy_algorithms::can_jump(std::vector<int>({2, 1, 4, 7})));
63
64 std::cout << "All tests have successfully passed!\n";
65}
66
71int main() {
72 test(); // run self-test implementations
73 return 0;
74}
static void test()
Function to test the above algorithm.
Definition jump_game.cpp:57
int main()
Main function.
Definition jump_game.cpp:71
for string class
bool can_jump(const std::vector< int > &nums)
Checks whether the given element (default is 1) can jump to the last index.
Definition jump_game.cpp:42