using
System;
using
System.Collections.Generic;
class
Program
{
static
List<List<
int
>> MinElementInKsizedSubMatrix(List<List<
int
>> matrix,
int
K)
{
int
n = matrix.Count;
int
m = matrix[0].Count;
List<List<
int
>> res =
new
List<List<
int
>>(n - K + 1);
for
(
int
i = 0; i < n - K + 1; i++)
{
res.Add(
new
List<
int
>(m - K + 1));
}
List<Queue<
int
>> deque =
new
List<Queue<
int
>>(m);
for
(
int
j = 0; j < m; j++)
{
deque.Add(
new
Queue<
int
>());
for
(
int
i = 0; i < K - 1; i++)
{
int
x = matrix[i][j];
while
(deque[j].Count > 0 && matrix[deque[j].Peek()][j] >= x)
deque[j].Dequeue();
deque[j].Enqueue(i);
}
}
for
(
int
i = K - 1; i < n; i++)
{
for
(
int
j = 0; j < m; j++)
{
int
x = matrix[i][j];
while
(deque[j].Count > 0 && matrix[deque[j].Peek()][j] >= x)
deque[j].Dequeue();
deque[j].Enqueue(i);
if
(deque[j].Count > 1 && deque[j].Peek() <= i - K)
deque[j].Dequeue();
}
Queue<Tuple<
int
,
int
>> dQ =
new
Queue<Tuple<
int
,
int
>>();
for
(
int
j = 0; j < K - 1; j++)
{
int
row = deque[j].Peek();
int
x = matrix[row][j];
while
(dQ.Count > 0 && matrix[dQ.Peek().Item1][dQ.Peek().Item2] >= x)
dQ.Dequeue();
dQ.Enqueue(
new
Tuple<
int
,
int
>(row, j));
}
for
(
int
j = K - 1; j < m; j++)
{
int
row = deque[j].Peek();
int
x = matrix[row][j];
while
(dQ.Count > 0 && matrix[dQ.Peek().Item1][dQ.Peek().Item2] >= x)
dQ.Dequeue();
dQ.Enqueue(
new
Tuple<
int
,
int
>(row, j));
if
(dQ.Count > 1 && dQ.Peek().Item2 <= j - K)
dQ.Dequeue();
res[i - K + 1].Add(matrix[dQ.Peek().Item1][dQ.Peek().Item2]);
}
}
return
res;
}
static
void
Main()
{
List<List<
int
>> matrix =
new
List<List<
int
>>
{
new
List<
int
> { -1, 5, 4, 1, -3 },
new
List<
int
> { 4, 3, 1, 1, 6 },
new
List<
int
> { 2, -2, 5, 3, 1 },
new
List<
int
> { 8, 5, 1, 9, -4 },
new
List<
int
> { 12, 3, 5, 8, 1 }
};
int
K = 3;
List<List<
int
>> res = MinElementInKsizedSubMatrix(matrix, K);
foreach
(
var
row
in
res)
{
foreach
(
var
col
in
row)
Console.Write(col +
" "
);
Console.WriteLine();
}
}
}