using System.Collections.Generic;
static char[][] createFarm(string s)
string cleaned = s.Replace("[", "").Replace("]", "").Replace(",", "");
string[] rows = cleaned.Split("||");
return rows.Select(r => r.ToCharArray())
static bool isSquareFarm(char[][] farm)
foreach (char[] row in farm)
if (row.Length != farm.Length)
static void lookAround(char currentChar, char[][] farm, int i, int j, HashSet<string> visited)
string key = i + "," + j;
if (visited.Contains(key))
Tuple<int, int>[] coordsToCheck =
foreach (Tuple<int, int> coord in coordsToCheck)
int x = coord.Item1, y = coord.Item2;
if (x < 0 || x >= farm.Length || y < 0 || y >= farm.Length) continue;
if (farm[x][y] != currentChar) continue;
lookAround(currentChar, farm, x, y, visited);
static int totalCost(string s)
char[][] farm = createFarm(s);
throw new Exception("Go away and come back with a square farm.");
HashSet<string> globalVisited = new HashSet<string>();
List<HashSet<string>> regions = new List<HashSet<string>>();
for (int i = 0; i < farm.Length; i++)
for (int j = 0; j < farm[i].Length; j++)
string key = i + "," + j;
if (globalVisited.Contains(key))
HashSet<string> region = new HashSet<string>();
lookAround(farm[i][j], farm, i, j, region);
foreach (string cell in region)
foreach (HashSet<string> region in regions)
string anyCell = region.First();
int anyI = int.Parse(anyCell.Split(',')[0]);
int anyJ = int.Parse(anyCell.Split(',')[1]);
char regionLetter = farm[anyI][anyJ];
foreach (string cell in region)
string[] parts = cell.Split(',');
int i = int.Parse(parts[0]);
int j = int.Parse(parts[1]);
if (i - 1 < 0 || farm[i - 1][j] != regionLetter) perimeter++;
if (i + 1 >= farm.Length || farm[i + 1][j] != regionLetter) perimeter++;
if (j - 1 < 0 || farm[i][j - 1] != regionLetter) perimeter++;
if (j + 1 >= farm.Length || farm[i][j + 1] != regionLetter) perimeter++;
totalCost += area * perimeter;
static void Main(string[] args)
string inputFarm = "[A,A,A,B||C,A,B,B||C,C,D,D||D,D,D,D]";
int cost = totalCost(inputFarm);
Console.WriteLine($"Total cost of the farm: {cost}");