using
System;
using
System.Collections.Generic;
using
System.Collections;
class
GFG{
static
int
lenOfLongSubarr(
int
[]arr,
int
n,
ref
int
start,
ref
int
finish)
{
Dictionary<
int
,
int
> um =
new
Dictionary<
int
,
int
>();
int
sum = 0, maxLen = 0;
for
(
int
i = 0; i < n; i++)
{
sum += arr[i];
if
(sum == 1)
{
start = 0;
finish = i;
maxLen = i + 1;
}
else
if
(!um.ContainsKey(sum))
um[sum] = i;
if
(um.ContainsKey(sum - 1))
{
if
(maxLen < (i - um[sum - 1]))
start = um[sum - 1] + 1;
finish = i;
maxLen = i - um[sum - 1];
}
}
return
maxLen;
}
static
void
largestSubmatrix(
int
[,]mat,
int
n)
{
int
finalLeft = 0, finalRight = 0,
finalTop = 0, finalBottom = 0;
int
maxArea = 0, len, start = 0, finish = 0;
int
[]temp =
new
int
[n];
for
(
int
left = 0; left < n; left++)
{
Array.Fill(temp, 0);
for
(
int
right = left; right < n; right++)
{
for
(
int
i = 0; i < n; ++i)
temp[i] += mat[i, right] == 0 ? -1 : 1;
len = lenOfLongSubarr(temp, n,
ref
start,
ref
finish);
if
((len != 0) &&
(maxArea < (finish - start + 1) *
(right - left + 1)))
{
finalLeft = left;
finalRight = right;
finalTop = start;
finalBottom = finish;
maxArea = (finish - start + 1) *
(right - left + 1);
}
}
}
Console.Write(
"(Top, Left): ("
+ finalTop +
", "
+ finalLeft +
")\n"
);
Console.Write(
"(Bottom, Right): ("
+ finalBottom +
", "
+ finalRight +
")\n"
);
Console.Write(
"Maximum area: "
+ maxArea);
}
public
static
void
Main(
string
[] args)
{
int
[,]mat =
new
int
[,]{ { 1, 0, 0, 1 },
{ 0, 1, 1, 1 },
{ 1, 0, 0, 0 },
{ 0, 1, 0, 1 } };
int
n = 4;
largestSubmatrix(mat, n);
}
}