AdventOfCode2025/AdventOfCode2025/Solutions/Day4.cs

95 lines
No EOL
2.6 KiB
C#

using AdventOfCode2025.Inputs;
namespace AdventOfCode2025.Solutions;
public class Day4() : Solution(4)
{
private const char NoneChar = '.';
private const char PaperChar = '@';
public override string SolvePart1()
{
var grid = PaddingField(Input.Lines)
.Select(line => line.ToCharArray())
.ToArray();
return GetRemovablePaper(grid).Count().ToString();
}
public override string SolvePart2()
{
var grid = PaddingField(Input.Lines)
.Select(line => line.ToCharArray())
.ToArray();
List<(int, int)> paperCanBeRemoved;
var paperCount = 0;
do
{
paperCanBeRemoved = GetRemovablePaper(grid).ToList();
paperCount += paperCanBeRemoved.Count;
foreach (var (row, col) in paperCanBeRemoved)
{
grid[row][col] = NoneChar;
}
} while (paperCanBeRemoved.Count > 0);
return paperCount.ToString();
}
private static IEnumerable<(int row, int col)> GetRemovablePaper(char[][] grid)
{
const int threshold = 3;
for (var row = 1; row < grid.Length - 1; row++)
{
for (var col = 1; col < grid[0].Length - 1; col++)
{
if (grid[row][col] != PaperChar)
{
continue;
}
if (!HasMorePaperNeighborsAs(col, row, threshold, grid))
{
yield return (row, col);
}
}
}
}
private static bool HasMorePaperNeighborsAs(int x, int y, int threshold, char[][] grid)
{
var directions = new (int dx, int dy)[] { (-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (0, 1), (-1, 1), (1, 1) };
var paperNeighbors = 0;
foreach (var (dx, dy) in directions)
{
var nx = x + dx;
var ny = y + dy;
if (nx < 0 || nx >= grid[0].Length || ny < 0 || ny >= grid.Length)
{
continue;
}
if (grid[ny][nx] != PaperChar)
{
continue;
}
paperNeighbors++;
if (paperNeighbors > threshold)
{
return true;
}
}
return false;
}
private IEnumerable<string> PaddingField(IEnumerable<string> field)
{
List<string> lines = field.ToList();
var width = lines.First().Length;
lines.Insert(0, new string(NoneChar, width));
lines.Add(new string(NoneChar, width));
return lines.Select(l => NoneChar + l + NoneChar);
}
}