using
System;
using
System.Collections.Generic;
class
Program
{
static
int
Dfs(
int
i,
int
j,
int
[][] grid,
bool
[][] visited,
int
key)
{
int
n = grid.Length;
if
(i < 0 || j < 0 || i >= n || j >= n || visited[i][j] || grid[i][j] == 0)
{
return
0;
}
visited[i][j] =
true
;
int
count = 1 +
Dfs(i + 1, j, grid, visited, key) +
Dfs(i - 1, j, grid, visited, key) +
Dfs(i, j + 1, grid, visited, key) +
Dfs(i, j - 1, grid, visited, key);
grid[i][j] = key;
return
count;
}
static
int
LargestIsland(
int
[][] grid)
{
int
n = grid.Length;
int
key = 2;
bool
[][] visited =
new
bool
[n][];
for
(
int
i = 0; i < n; i++)
{
visited[i] =
new
bool
[n];
}
Dictionary<
int
,
int
> unmap =
new
Dictionary<
int
,
int
>();
for
(
int
i = 0; i < n; i++)
{
for
(
int
j = 0; j < n; j++)
{
if
(!visited[i][j] && grid[i][j] == 1)
{
int
count = Dfs(i, j, grid, visited, key);
unmap[key] = count;
key++;
}
}
}
int
result = -1;
bool
[][] visited2 =
new
bool
[n][];
for
(
int
i = 0; i < n; i++)
{
visited2[i] =
new
bool
[n];
}
for
(
int
i = 0; i < n; i++)
{
for
(
int
j = 0; j < n; j++)
{
if
(grid[i][j] == 0)
{
int
a = (i + 1 < n) ? grid[i + 1][j] : 0;
int
b = (i - 1 >= 0) ? grid[i - 1][j] : 0;
int
c = (j + 1 < n) ? grid[i][j + 1] : 0;
int
d = (j - 1 >= 0) ? grid[i][j - 1] : 0;
HashSet<
int
> st =
new
HashSet<
int
>();
st.Add(a);
st.Add(b);
st.Add(c);
st.Add(d);
int
res = 1;
foreach
(
int
value
in
st)
{
if
(unmap.ContainsKey(value))
{
res += unmap[value];
}
}
result = Math.Max(result, res);
}
}
}
if
(result == -1)
{
return
n * n;
}
return
result;
}
static
void
Main()
{
int
[][] grid = {
new
int
[] { 1, 0, 1, 1, 0 },
new
int
[] { 1, 0, 0, 1, 0 },
new
int
[] { 0, 1, 1, 0, 1 },
new
int
[] { 1, 0, 1, 0, 1 },
new
int
[] { 0, 1, 0, 1, 0 }
};
int
largestIslandSize = LargestIsland(grid);
Console.WriteLine(
"Largest island size: "
+ largestIslandSize);
}
}