Ocean

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
					
public class Program
{
    private static int MaxIsland(int[,] ocean) {
        int result = 0;

        if (ocean == null)
            return result;

        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 (ocean[y, x] != 0)
                     continue;
      
				 if (!visited.Add((y, x)))
                     continue;

                 int current = 1;
                 
				 var agenda = new Queue<(int y, int x)>();

                 agenda.Enqueue((y, 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))
                             continue;
                         if (ocean[newR, newC] != 0)
                             continue;
						 
                         if (visited.Add((newR, newC))) {
                             agenda.Enqueue((newR, newC));
                             
							 current += 1;
                         }
                     }
                 }

                 result = Math.Max(result, current);
             }

        return result;
    }
	
	public static void Main()
	{
		int[,] ocean = {
            { 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);
		
		Console.Write(result);
	}
}
;