We are given a two-dimensional rectangular array (matrix) of integers and to find the sub-matrix of the size of 2 by 2 with a maximum sum of its elements and to print it.
class AddMaxNumber
{
static void Main()
{
// Declare and
initialize the matrix
int[,] matrix = {
{ 0, 2, 4, 0, 9, 3 },
{ 7, 1, 6, 3, 2, 1 },
{ 1, 3, 5, 8, 5, 6 },
{ 4, 6, 7, 9, 1, 0 }
};
// Find the
maximam sum platform of size 2 x 2
long maxSum = long.MinValue;
int maxRow = 0;
int maxCol = 0;
for (int row = 0;
row < matrix.GetLength(0) - 1; row++)
{
for (int col = 0;
col < matrix.GetLength(1) - 1; col++)
{
long sum = matrix[row, col] +
matrix[row, col + 1] +
matrix[row + 1, col] +
matrix[row + 1, col + 1];
if (sum > maxSum)
{
maxSum = sum;
maxRow = row;
maxCol = col;
}
}
}
// Print the
result
Console.WriteLine("The max matrix platform is:");
Console.WriteLine(" {0} {1}",
matrix[maxRow, maxCol],
matrix[maxRow, maxCol +
1]);
Console.WriteLine(" {0} {1}",
matrix[maxRow + 1, maxCol],
matrix[maxRow + 1, maxCol + 1]);
Console.WriteLine("The maximam sum is: {0}", maxSum);
Console.ReadLine();
}
}
Output:
No comments:
Post a Comment