|
| 1 | +namespace AdventOfCode.Puzzles._2025._04.Part2; |
| 2 | + |
| 3 | +public class AoC2025Day4Part2 : IPuzzleSolution |
| 4 | +{ |
| 5 | + private const char Roll = '@'; |
| 6 | + private char[,] _map; |
| 7 | + private int _width; |
| 8 | + private int _height; |
| 9 | + |
| 10 | + public async Task<string> SolveAsync(StreamReader inputReader) |
| 11 | + { |
| 12 | + var lines = await inputReader.ReadAllLinesAsync(); |
| 13 | + _width = lines[0].Length; |
| 14 | + _height = lines.Count; |
| 15 | + _map = new char[lines[0].Length, lines.Count]; |
| 16 | + for (int x = 0; x < _width; x++) |
| 17 | + { |
| 18 | + for (int y = 0; y < _height; y++) |
| 19 | + { |
| 20 | + _map[x, y] = lines[y][x]; |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + var total = 0; |
| 25 | + while (true) |
| 26 | + { |
| 27 | + var movablePositions = FindMovable(); |
| 28 | + if (movablePositions.Length == 0) |
| 29 | + { |
| 30 | + break; |
| 31 | + } |
| 32 | + |
| 33 | + total += movablePositions.Length; |
| 34 | + |
| 35 | + foreach (var pos in movablePositions) |
| 36 | + { |
| 37 | + _map[pos.X, pos.Y] = '.'; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return total.ToString(); |
| 42 | + } |
| 43 | + |
| 44 | + private Point[] FindMovable() |
| 45 | + { |
| 46 | + var positions = new List<Point>(); |
| 47 | + for (int y = 0; y < _height; y++) |
| 48 | + { |
| 49 | + for (int x = 0; x < _width; x++) |
| 50 | + { |
| 51 | + if (_map[x, y] == Roll && IsMovable(x, y)) |
| 52 | + { |
| 53 | + positions.Add(new Point(x, y)); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return positions.ToArray(); |
| 59 | + } |
| 60 | + |
| 61 | + private bool IsMovable(int x, int y) |
| 62 | + { |
| 63 | + var adjacentRolls = 0; |
| 64 | + foreach (var direction in Directions.WithDiagonals) |
| 65 | + { |
| 66 | + var neighborPosition = new Point(x + direction.X, y + direction.Y); |
| 67 | + if (neighborPosition.X < 0 || neighborPosition.X >= _width || |
| 68 | + neighborPosition.Y < 0 || neighborPosition.Y >= _height) |
| 69 | + { |
| 70 | + continue; |
| 71 | + } |
| 72 | + |
| 73 | + if (_map[neighborPosition.X, neighborPosition.Y] == Roll) |
| 74 | + { |
| 75 | + adjacentRolls++; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return adjacentRolls < 4; |
| 80 | + } |
| 81 | +} |
0 commit comments