o(n) 中的 C# 中的解决方案。
建立一个帮助矩阵来检查每个步骤,看看到达那里的最小方法是什么,然后添加一个。
const int BoardSize = 100;
const int MaxStep = 6;
static void Main()
{
// - means a ledder ending at the pos
// + means a snake (taking you back n steps)
int[] arr = new int[] {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 8, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -71, -1, -1 };
Console.WriteLine("Steps needed: " + solve(arr));
}
public static int solve(int[] inArr)
{
int[] arr = new int[BoardSize];
arr[0] = 1;
for (int i = 0; i < BoardSize; ++i)
{
// steps here is the minimum of all the positions in all the previos 6 cells +1
if (i < MaxStep)
arr[i] = 1;
else
{
int extraOption = int.MaxValue;
if (inArr[i] < -1 || inArr[i] > 0)
extraOption = arr[i + inArr[i]];
else if (inArr[i] > 0)
extraOption = arr[i + inArr[i]];
arr[i] = min(arr[i - 1], arr[i - 2], arr[i - 3], arr[i - 4], arr[i - 5], arr[i - 6], extraOption) + 1;
}
}
for (int i = 0; i < BoardSize; ++i)
{
Console.Write(arr[i] + "\t");
if ((i + 1) % 10 == 0)
Console.WriteLine("");
}
return arr[arr.Length-1];
}
public static int min(int a, int b, int c, int d, int e, int f, int g)
{
int ab = Math.Min(a,b);
int cd = Math.Min(c,d);
int ef = Math.Min(e,f);
return Math.Min(Math.Min(ab, cd), Math.Min(ef,g));
}