How to find the minimum number of jumps required to reach the end of the array using C#?

CsharpServer Side ProgrammingProgramming

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

Example

 Live Demo

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

4
raja
Published on 27-Aug-2021 12:50:05
Advertisements