using System;
using System.IO;
namespace _2021___Day_11
{
class Program
{
public static int flashes = 0;
public static int[,] octoMap;
static void Main(string[] args)
{
string[] input = File.ReadAllLines("../../../../Input.in");
int xSize = input[0].Length;
int ySize = input.Length;
octoMap = new int[xSize, ySize];
for (int y = 0; y < ySize; y++)
{
for (int x = 0; x < xSize; x++)
{
octoMap[x, y] = int.Parse(input[y][x].ToString());
}
}
for (int steps = 1; steps < 1000; steps++)
{
for (int y = 0; y < ySize; y++)
{
for (int x = 0; x < xSize; x++)
{
octoMap[x, y] += 1;
}
}
for (int y = 0; y < ySize; y++)
{
for (int x = 0; x < xSize; x++)
{
if (octoMap[x, y] > 9)
{
Flash(x, y, xSize, ySize);
}
}
}
if (octoMap[0, 0] == 0 && octoMap[xSize - 1, 0] == 0 && octoMap[0, ySize - 1] == 0 && octoMap[xSize - 1, ySize - 1] == 0)
{
int counter = 0;
for (int y = 0; y < ySize; y++)
{
for (int x = 0; x < xSize; x++)
{
if (octoMap[x, y] == 0)
counter++;
}
}
if (counter == xSize * ySize)
{
Console.WriteLine("There needs to be " + steps.ToString() + "for them to all synchronize");
break;
}
}
if (steps == 100)
{
Console.WriteLine("After Step 100, there have been " + flashes.ToString() + " flashes");
}
}
}
public static void Flash(int x, int y, int xSize, int ySize)
{
flashes++;
octoMap[x, y] = 0;
Energize(x, y, xSize, ySize);
}
public static void Energize(int x, int y, int xSize, int ySize)
{
for (int r = y - 1; r <= y + 1; r++)
{
for (int c = x - 1; c <= x + 1; c++)
{
if ((r >= 0 && r < ySize) && (c >= 0 && c < xSize))
{
if (octoMap[c, r] != 0)
{
octoMap[c, r]++;
}
if (octoMap[c, r] > 9)
{
Flash(c, r, xSize, ySize);
}
}
}
}
}
}
}