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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # Returns minimum number of jumps to reach arr[n-1] from arr[0] def minJumps(arr, n): jumps = [0 for i in range(n)] if (n == 0) or (arr[0] == 0): return float('inf') jumps[0] = 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) break return jumps[n-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)) |
Program Output
1 | 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.