【问题标题】:Browse a matrix浏览矩阵
【发布时间】:2012-08-14 12:47:14
【问题描述】:

我想浏览像这样的矩阵:

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

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

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

【问题讨论】:

  • 您在矩阵中的搜索将在什么时候终止?到目前为止,这听起来像是可以通过两个嵌套循环轻松完成的事情。
  • 这是 C# 中的二维数组结构吗?你已经有什么代码了?在这种情况下,动词“浏览”也让我感到困惑。

标签: c# matrix


【解决方案1】:

您需要遍历矩阵的上/下半部分吗?我假设一个矩阵是一个 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;
    }
}

虽然,我不太明白

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

部分。

【讨论】:

    【解决方案2】:

    这里是我找到的解决方案:

        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;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多