【问题标题】:Square with Maximum Sum最大和的平方
【发布时间】:2019-10-07 15:38:24
【问题描述】:

我正在学习 C#,目前正在做多维数组。我想编写一个程序,读取一个矩阵,然后找到 2x2 子矩阵的最大总和并打印出来。

int[] dimensions = Console.ReadLine()
            .Split(", ", StringSplitOptions.RemoveEmptyEntries)
            .Select(int.Parse)
            .ToArray();

int rows = dimensions[0];
int columns = dimensions[1];

int[,] matrix = new int[rows,columns];

for (int i = 0; i < rows; i++)
{
     int[] numbers = Console.ReadLine()
                .Split(", ", StringSplitOptions.RemoveEmptyEntries)
                .Select(int.Parse)
                .ToArray();

     for (int j = 0; j < columns; j++)
     {
          matrix[i, j] = numbers[j];
     }
 }

int maxSum = int.MinValue;
        int selectedRow = -1;
        int selectedCol = -1;

        for (int row = 0; row < matrix.GetLength(0) - 1; row++)
        {
            for (int col = 0; col < matrix.GetLength(1) - 1; col++)
            {
                int currentSum = matrix[row, col] + matrix[row, col + 1] + matrix[row + 1, col] + matrix[row + 1, col + 1];

                if (currentSum > maxSum)
                {
                    maxSum = currentSum;
                    selectedRow = row;
                    selectedCol = col;
                }

            }
        }

        Console.WriteLine($"{matrix[selectedRow, selectedCol]} {matrix[selectedRow, selectedCol + 1]}");
        Console.WriteLine($"{matrix[selectedRow + 1, selectedCol]} {matrix[selectedRow + 1, selectedCol + 1]}");
        Console.WriteLine(maxSum);

所以,我阅读了矩阵,但不知道如何开始查找子矩阵比较它们的总和。如果您能给我一些提示,我将不胜感激。

【问题讨论】:

  • 一个好的开始是编写一个函数,该函数能够通过传递矩阵和 rowOffset、columnOffset 并返回总和来检查 2x2 矩阵。然后循环检查row.Length-2和column.Length-2。当结果高于前一个最大总和时保存行/列。
  • 您需要检查下、下、左和右的项目。例如,您可以这样做:[i+1, j]、[i-1, j+1] 等等。只需使用索引加或减 1。不要忘记检查您是否不会指向数组之外的索引。
  • 听起来你需要做的只是:弄清楚如何对单个子矩阵求和,例如从位置 (x,y) 开始的子矩阵,b:在二维上写一个循环,考虑子矩阵的大小,计算每个可能的子矩阵的和,c:选择最大的?我不认为人们会想要为你做这个(这听起来像是家庭作业,你不会因为不做而学到任何东西) - 所以:你到哪里去了?
  • 这是你试图得到的总和 stackoverflow.com/a/56225711/6299857... 找到 2x2 矩阵你到目前为止尝试过的东西
  • @MarcGravell,我已经更新了我的代码。如果您能看到,我将不胜感激。 :)

标签: c# matrix multidimensional-array


【解决方案1】:

您只需要检查 i 的当前位置j 的当前右侧 位置的值强>。

我的意思是它会像这样检查:

  • [7,1] [1,3] [3,3]
  • [1,3] [3,9] [9,8]

等等。

每次比较后,计算这个 2x2 矩阵的总和并将其保存到字典中。 返回时,只需要找到key的最大值,获取key的值即可。

public class MatrixTest
    {
        public static IEnumerable<object[]> TestData =>
            new List<object[]>
            {
                new object[]
                {
                    new int[,]
                    {
                        {7, 1, 3, 3, 2, 1},
                        {1, 3, 9, 8, 5, 6},
                        {4, 6, 7, 9, 1, 0}
                    },
                    new int[,]
                    {
                        {9, 8},
                        {7, 9}
                    },
                    33
                },
                new object[]
                {
                    new int[,]
                    {
                        {10, 11, 12, 13},
                        {14, 15, 16, 17}
                    },
                    new int[,]
                    {
                        {12, 13},
                        {16, 17}
                    },
                    58
                }
            };


        [Theory]
        [MemberData(nameof(TestData))]
        public void Test(int[,] input, int[,] expectedArray, int expectedSum)
        {
            MatrixHandler m = new MatrixHandler();

            var resp = m.GetMax2x2Matrix(input);

            resp.Item1.Should().Be(expectedSum);

            resp.Item2.Should().BeEquivalentTo(expectedArray);
        }
    }


    public class MatrixHandler
    {
        public (int, int[,]) GetMax2x2Matrix(int[,] source)
        {
            var sumsPlusTempArrays = new Dictionary<int, int[,]>();

            int[,] temp;
            int sum = 0;

            for (int i = 0, n0 = source.GetLength(0) - 1; i <= n0; i++)
            {
                for (int j = 0, n1 = source.GetLength(1) - 1; j <= n1; j++)
                {
                    if (i + 1 <= n0 && j + 1 <= n1)
                    {
                        temp = new int[2,2];
                        temp[0, 0] = source[i, j];
                        temp[0, 1] = source[i, j + 1];
                        temp[1, 0] = source[i + 1, j];
                        temp[1, 1] = source[i + 1, j + 1];
                        sum = CalculateSum(temp);
                        sumsPlusTempArrays.TryAdd(sum, temp);
                    }
                }
            }

            var key = sumsPlusTempArrays.Select(x => x.Key).Max();

            var value = sumsPlusTempArrays[key];

            return (key, value);
        }

        private int CalculateSum(int[,] source)
        {
            int sum = 0;

            for (int i = 0, n0 = source.GetLength(0); i < n0; i++)
            {
                for (int j = 0, n1 =  source.GetLength(1); j < n1; j++)
                {
                    sum += source[i, j];
                }
            }
            return sum;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-29
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    相关资源
    最近更新 更多