bool canJump(int jumpPowers[], int n) { vector<bool> canReachEnd(n, false); canReachEnd[n-1] = true; int p = n - 1; while (true) { if (canReachEnd[0]) { return true; } if (p == 0) { return false; } for (int i = 0; i < p; ++i) { if (canReachEnd[i]) { continue; } if (jumpPowers[i] + i >= p) { canReachEnd[i] = true; } } while (p > 0) { if (canReachEnd[--p]) { break; } } } }
bool CanReachEnd::test() { int temp_arr1[] = { 3, 3, 1, 0, 2, 0, 1 }; vector<int> a ( temp_arr1, temp_arr1 + sizeof(temp_arr1) / sizeof(temp_arr1[0]) ); int temp_arr2[] = { 3, 2, 0, 0, 2, 0, 1 }; vector<int> b ( temp_arr2, temp_arr2 + sizeof(temp_arr2) / sizeof(temp_arr2[0]) ); cout << "In " << vec_to_string(a) << ", can "; if (!canReachEnd(a)) cout << "not "; cout << "reach the end. " << endl; cout << "In " << vec_to_string(b) << ", can "; if (!canReachEnd(b)) cout << "not "; cout << "reach the end. " << endl; return true; }