In: Computer Science
Input: An array of non-negative integers, where each element in the array represents your maximum jump length at that position.
Output: A boolean value if you are able to reach the last index starting if you start at the first spot in the array.
[Please write a recursion function!]
Example 1:
Example 2:
Dear Learner,
Here is the code for your answer,
def jumpfunction(i,A,iteR=0): #the i is the beginning index to
start from
#we will take an additional parameter so as to stop
the function from going in infinite loop
if iteR<len(A): #checking if we have exceeded the
max number of iterations
if(i==(len(A)-1)): #we are checking
if we have reached the end of the list
return
bool(True) #returning the result
else:
return
jumpfunction(i+A[i],A,iteR+1) #recursive call to the remaining part
of the array
else:
return bool(False) #returning false
as we have crossed the maximum value
A = [3,2,1,0,4]
result = bool(jumpfunction(0,A)) #calling the function and storing
the result in 'result' variable
print(result)
SCREENSHOT OF CODE :-
CORRESPONDING OUTPUT:-
FOR ANOTHER INPUT
Note that I have taken static values for the array, but the code will be the same for dynamic values as well.
I hope I have answered the question the way you were expecting. If you still have any doubts or want any other explanation, feel free to ask us in the comment section.
Please leave a like if this was helpful.
Thanks,
Happy Studying.