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
33
namespace
greedy_algorithms
{
42
bool
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
57
static
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
71
int
main
() {
72
test
();
// run self-test implementations
73
return
0;
74
}
test
static void test()
Function to test the above algorithm.
Definition
jump_game.cpp:57
main
int main()
Main function.
Definition
jump_game.cpp:71
greedy_algorithms
for string class
Definition
binary_addition.cpp:27
greedy_algorithms::can_jump
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
greedy_algorithms
jump_game.cpp
Generated by
1.12.0