Want to write a Python program to find Minimum number of jumps to reach end. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element).
Use the following Python program and execute to see the program output.
# Returns minimum number of jumps to reach arr[n-1] from arr
def minJumps(arr, n):
jumps = [0 for i in range(n)]
if (n == 0) or (arr == 0):
jumps = 0
for i in range(1, n):
jumps[i] = float('inf')
for j in range(i):
if (i <= j + arr[j]) and (jumps[j] != float('inf')):
jumps[i] = min(jumps[i], jumps[j] + 1)
# Main function to test above function
arr = [1, 3, 6, 1, 0, 9]
size = len(arr)
print('Minimum number of jumps to reach',
'end is', minJumps(arr,size))
Minimum number of jumps to reach end is 3
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.