如何使用 C# 找到到达数组末尾所需的最小跳转次数?

我们可以简单地从第一个元素开始,并重复调用从第一个元素到达的所有元素。从第一个到达终点的最小跳转次数可以使用从第一个可到达的元素到达终点所需的最小跳转次数来计算。

数组 == {1, 3, 6, 3, 2, 3, 6, 8, 9, 5};

所需步骤数为 4

示例

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(" 到达终点的最少跳跃次数为 " + a.MinJumps(arrm, 0, n - 1));
      }
   }
}
输出结果
4

猜你喜欢