-5

我想浏览像这样的矩阵:

我要浏览的矩阵示例

我想浏览第一行,得到最小的数字,然后浏览与前一个最小数字匹配的行。

例如:我浏览 A 行:我浏览单元格 A,A,我得到 0。我不保留它(因为它是 0)我浏览单元格 A,DI 得到 5。我保留它。我浏览单元格 A,GI 得到 8,但我不保留它,因为它优于 5。我浏览单元格 A,K,得到 4 我保留它(< 5)。

目前没关系,一个简单的循环就足够了。然后我想浏览K行,如果可能的话不要浏览单元格K,A,因为我在浏览A行时已经浏览过它。

4

2 回答 2

0

您需要遍历矩阵的上/下半部分吗?我假设矩阵是一个 int 数组的数组。

var matrix = new int[][]{ ... };
int smallest = 0;
for(int i = 0; i < matrix.Length; i++)
{
    for(int j = 0; j < matrix.Length; j++)
    {
        int number = matrix[i][j];
        if (number != 0 && number < smallest)
            smallest = number;
    }
}

虽然,我没有完全明白

然后浏览与前一个最小数字匹配的行

部分。

于 2012-08-14T13:25:00.180 回答
0

这是我找到的解决方案:

    private static IEnumerable<int> ComputeMatrix(int[,] matrix)
    {
        // check args
        if (matrix.Rank != 2) { throw new ArgumentException("matrix should have a rank of 2"); }
        if (matrix.GetUpperBound(0) != matrix.GetUpperBound(1)) { throw new ArgumentException("matrix should have the same size");}

        // indice treated
        List<int> treatedIndex = new List<int>();

        for (int i = 0; i <= matrix.GetUpperBound(0); i++)
        {
            if (treatedIndex.Count == matrix.GetUpperBound(0)) 
                break;

            // distance minimum between 2 points
            int distanceMin = Int32.MaxValue;

            // next iteration of index
            int nextI = i;

            // add the index to ignore in the next iteration
            int nextJ = -1;

            for (int j = 0; j <= matrix.GetUpperBound(1); j++)
            {
                if (treatedIndex.IndexOf(j) == -1)
                {
                    if (matrix[i, j] != 0 && matrix[i, j] < distanceMin)
                    {
                        distanceMin = matrix[i, j];
                        nextI = j;
                        nextJ = i;
                    }
                }
            }

            i = nextI - 1;
            treatedIndex.Add(nextJ);
            yield return distanceMin;
        }
    }
于 2012-08-16T13:09:14.870 回答