0% found this document useful (0 votes)
22 views

Minimum Number of Jumps To Reach End

The document describes a minimum number of jumps problem where given an array representing max steps forward from each element, the function returns the minimum number of jumps to reach the end of the array starting from the first element. It provides a minJumps function that recursively gets the minimum jumps needed to reach the end and returns the result. It includes a driver program that tests the function on a sample array.

Uploaded by

sethuraman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Minimum Number of Jumps To Reach End

The document describes a minimum number of jumps problem where given an array representing max steps forward from each element, the function returns the minimum number of jumps to reach the end of the array starting from the first element. It provides a minJumps function that recursively gets the minimum jumps needed to reach the end and returns the result. It includes a driver program that tests the function on a sample array.

Uploaded by

sethuraman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Minimum number of jumps to reach end

Given an array of integers where each element represents the max number of steps that can be
made forward from that element. Write a function to return the minimum number of jumps to
reach the end of the array (starting from the first element). If an element is 0, they cannot move
through that element. If the end isn’t reachable, return -1.

def minJumps(arr, l, h):

# Base case: when source and


# destination are same
if (h == l):
return 0

# when nothing is reachable


# from the given source
if (arr[l] == 0):
return float('inf')

# Traverse through all the points


# reachable from arr[l]. Recursively
# get the minimum number of jumps
# needed to reach arr[h] from
# these reachable points.
min = float('inf')
for i in range(l + 1, h + 1):
if (i < l + arr[l] + 1):
jumps = minJumps(arr, i, h)
if (jumps != float('inf') and
jumps + 1 < min):
min = jumps + 1

return min

# Driver program to test above function


arr = [1, 3, 6, 3, 2, 3, 6, 8, 9, 5]
n = len(arr)
print('Minimum number of jumps to reach',
'end is', minJumps(arr, 0, n-1))

# This code is contributed by Soumen Ghosh


reference - geeksforgeeks

You might also like