In this example,i’ll show you How to find the minimum number of jumps required to reach the end of the array using C#.
We can simply start from the first element and repeatedly call for all the elements reachable from first element. The minimum number of jumps to reach end from first can be calculated using minimum number of jumps needed to reach end from the elements reachable from first.
Array == {1, 3, 6, 3, 2, 3, 6, 8, 9, 5};
Number of steps required is 4.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; namespace ConsoleApplication{ public class Arrays{ public int MinJumps(int[] arr, int l, int h){ if (h == l) return 0; if (arr[l] == 0) return int.MaxValue; int min = int.MaxValue; for (int i = l + 1; i <= h && i <= l + arr[l]; i++){ int jumps = MinJumps(arr, i, h); if (jumps != int.MaxValue && jumps + 1 < min) min = jumps + 1; } return min; } } class Program{ static void Main(string[] args){ Arrays a = new Arrays(); int[] arrm = { 1, 3, 6, 3, 2, 3, 6, 8, 9, 5 }; int n = arrm.Length; Console.Write(" Minimum number of jumps to reach end is " + a.MinJumps(arrm, 0, n - 1)); } } } |
Output:
1 2 3 |
4 |