using
System;
using
System.Collections.Generic;
class
Program
{
static
List<List<
int
>> MaxSumSubmatrix(List<List<
int
>> matrix,
int
size)
{
int
rows = matrix.Count;
int
cols = matrix[0].Count;
List<List<
int
>> dp =
new
List<List<
int
>>();
for
(
int
i = 0; i < rows; i++)
{
dp.Add(
new
List<
int
>());
for
(
int
j = 0; j < cols; j++)
{
dp[i].Add(0);
}
}
for
(
int
i = 0; i < rows; i++)
{
for
(
int
j = 0; j < cols; j++)
{
dp[i][j] = matrix[i][j];
if
(i > 0) dp[i][j] += dp[i - 1][j];
if
(j > 0) dp[i][j] += dp[i][j - 1];
if
(i > 0 && j > 0) dp[i][j] -= dp[i - 1][j - 1];
}
}
int
maxSum =
int
.MinValue;
List<List<
int
>> maxSubmatrix =
new
List<List<
int
>>();
for
(
int
i = size - 1; i < rows; i++)
{
for
(
int
j = size - 1; j < cols; j++)
{
int
submatrixSum = dp[i][j];
if
(i >= size) submatrixSum -= dp[i - size][j];
if
(j >= size) submatrixSum -= dp[i][j - size];
if
(i >= size && j >= size) submatrixSum += dp[i - size][j - size];
if
(submatrixSum > maxSum)
{
maxSum = submatrixSum;
maxSubmatrix.Clear();
for
(
int
r = i - size + 1; r <= i; r++)
{
List<
int
> row =
new
List<
int
>();
for
(
int
c = j - size + 1; c <= j; c++)
{
row.Add(matrix[r]);
}
maxSubmatrix.Add(row);
}
}
}
}
return
maxSubmatrix;
}
static
void
Main(
string
[] args)
{
List<List<
int
>> matrix =
new
List<List<
int
>>
{
new
List<
int
> {1, 1, 1, 1, 1},
new
List<
int
> {2, 2, 2, 2, 2},
new
List<
int
> {3, 8, 6, 7, 3},
new
List<
int
> {4, 4, 4, 4, 4},
new
List<
int
> {5, 5, 5, 5, 5}
};
int
size = 3;
List<List<
int
>> maxSubmatrix = MaxSumSubmatrix(matrix, size);
Console.WriteLine(
"Maximum sum "
+ size +
" x "
+ size +
" matrix is:"
);
foreach
(List<
int
> row
in
maxSubmatrix)
{
foreach
(
int
x
in
row)
{
Console.Write(x +
" "
);
}
Console.WriteLine();
}
}
}