using System.Collections.Generic;
private static int MaxIsland(int[,] ocean) {
var visited = new HashSet<(int y, int x)>();
for (int y = 0; y < ocean.GetLength(0); ++y)
for (int x = 0; x < ocean.GetLength(1); ++x) {
if (!visited.Add((y, x)))
var agenda = new Queue<(int y, int x)>();
while (agenda.Count > 0) {
var (r, c) = agenda.Dequeue();
for (int d = 0; d < 4; ++d) {
int newR = r + (d - 1) % 2;
int newC = c + (d - 2) % 2;
if (newC < 0 || newR < 0 || newR >= ocean.GetLength(0) || newC >= ocean.GetLength(1))
if (ocean[newR, newC] != 0)
if (visited.Add((newR, newC))) {
agenda.Enqueue((newR, newC));
result = Math.Max(result, current);
public static void Main()
{ 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, },
{ 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, },
{ 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, },
{ 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, },
{ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, },
{ 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, },
{ 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, },
int result = MaxIsland(ocean);