Inactive Tutor answered 04/08/22
You could do it with something like this:
bool canReach(vector<vector<int>>& batteries, int start, vector<bool>& visited) {
// If we've gone past the end with a previous battery, then we can return true
if (start >= batteries.size()) {
return true;
}
// Otherwise, check if we've tried this before
if (visited[start]) {
return false;
}
// Then check if we can reach the end from here, recursively
for (int i=0; i<batteries[start].size(); i++) {
int charge = batteries[start][i];
if (canReach(grid, start+charge, visited)) {
return true;
}
}
// Finally, mark that we've tried and failed here and return out
visited[start] = true;
return false;
}
Inactive Tutor
Alternatively, you could do this iteratively using a stack or a queue, but I think the recursive solution is more intuitive.04/08/22
Inactive Tutor
My solution assumes that it's ok to waste some charge of the last battery because you can have enough charge to bike past the endpoint. If that assumption is invalid, then we just need to change the base case of the recursion a little bit.04/08/22