【问题标题】:C#. Min path from left top corner to right bottom on ( n x n ) tableC#。 ( n x n ) 表上从左上角到右下角的最小路径
【发布时间】:2017-04-06 07:43:24
【问题描述】:

我的代码有问题,我明白了

System.IndexOutOfRangeException

find() 方法的第一个循环中。
你们能帮帮我吗?我不知道出了什么问题。

我为 java 找到了这段代码,并为 C# 做了一些改动。在java代码中有int[][] A,我把它改成了int[,]。 P.S on java,代码有效。

class Program
{
    static void Main(string[] args)
    {
        int[,] A = { { 1, 7, 9, 2 }, { 8, 6, 3, 2 }, { 1, 6, 7, 8 },
            { 2, 9, 8, 2 } };
        Console.WriteLine("{0}", find(A));
    }

    public static int find(int[,] A)
    {
        int[,] solution = new int[A.Length + 1, A.Length + 1];

        solution[0, 0] = A[0, 0];

        for(int i = 1; i < A.Length; i++)
        {
            solution[0, i] = A[0, i] + solution[0, i - 1]; //IndexOutOfRangeException
        }

        for(int i = 1; i < A.Length; i++)
        {
            solution[i, 0] = A[i, 0] + solution[i - 1, 0];
        }

        for(int i = 1; i < A.Length; i++)
        {
            for(int j = 1; j < A.Length; j++)
            {
                solution[i, j] = A[i, j] 
                    + Math.Min(solution[i - 1, j], solution[i, j - 1]);
            }
        }
        return solution[A.Length - 1, A.Length - 1];
    }
}

【问题讨论】:

  • 你需要知道哪一行是第 26 行。
  • 我说过。 find() 方法中的第一个循环。 "解决方案[0, i] = A[0, i] + 解决方案[0, i - 1];"
  • 你认为答案是 29 吗?
  • 是的。我现在29。但也许有人知道如何改变它,它会找到 MAX 路径?
  • 您希望答案是什么? 40 ?

标签: c# dynamic-programming indexoutofrangeexception


【解决方案1】:

问题在于,在锯齿状数组 ([,]) 中,Length 属性将为您提供元素的总量,在您的情况下为 A.Length == 16,但您只需要一个维度。解决方案是使用GetLength

for (int i = 1; i < A.GetLength(1); i++)

X 维度需要使用0,Y 维度需要使用1 ([X,Y])
请参阅documenation 了解详情。

你的方法应该是这样的:

public static int find(int[,] A)
{
    int[,] solution = new int[A.GetLength(0) + 1, A.GetLength(1)+ 1];

    solution[0, 0] = A[0, 0];

    for (int i = 1; i < A.GetLength(1); i++)
    {
        solution[0, i] = A[0, i] + solution[0, i - 1];
    }

    for (int i = 1; i < A.GetLength(0); i++)
    {
        solution[i, 0] = A[i, 0] + solution[i - 1, 0];
    }

    for (int i = 1; i < A.GetLength(0); i++)
    {
        for (int j = 1; j < A.GetLength(1); j++)
        {
            solution[i, j] = A[i, j]
                + Math.Min(solution[i - 1, j], solution[i, j - 1]);
        }
    }
    return solution[A.GetLength(0) - 1, A.GetLength(1) - 1];
}

【讨论】:

  • 谢谢!你救了我。 :)
  • 不客气。调试有助于找出您遇到越界的原因:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-25
  • 2019-09-17
  • 1970-01-01
  • 2019-03-06
  • 2020-05-01
相关资源
最近更新 更多