|
| 1 | +import com.github.pareronia.aoc.CharGrid; |
| 2 | +import com.github.pareronia.aoc.Grid.Cell; |
| 3 | +import com.github.pareronia.aoc.solution.Sample; |
| 4 | +import com.github.pareronia.aoc.solution.Samples; |
| 5 | +import com.github.pareronia.aoc.solution.SolutionBase; |
| 6 | + |
| 7 | +import java.util.ArrayDeque; |
| 8 | +import java.util.Deque; |
| 9 | +import java.util.HashSet; |
| 10 | +import java.util.List; |
| 11 | +import java.util.Set; |
| 12 | + |
| 13 | +@SuppressWarnings({"PMD.ClassNamingConventions", "PMD.NoPackage"}) |
| 14 | +public final class AoC2025_04 extends SolutionBase<CharGrid, Long, Long> { |
| 15 | + |
| 16 | + public static final char ROLL = '@'; |
| 17 | + public static final char EMPTY = '.'; |
| 18 | + |
| 19 | + private AoC2025_04(final boolean debug) { |
| 20 | + super(debug); |
| 21 | + } |
| 22 | + |
| 23 | + public static AoC2025_04 create() { |
| 24 | + return new AoC2025_04(false); |
| 25 | + } |
| 26 | + |
| 27 | + public static AoC2025_04 createDebug() { |
| 28 | + return new AoC2025_04(true); |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + protected CharGrid parseInput(final List<String> inputs) { |
| 33 | + return CharGrid.from(inputs); |
| 34 | + } |
| 35 | + |
| 36 | + private boolean isRemovable(final CharGrid grid, final Cell cell) { |
| 37 | + return grid.getValue(cell) == ROLL |
| 38 | + && grid.getAllNeighbours(cell).filter(n -> grid.getValue(n) == ROLL).count() < 4; |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public Long solvePart1(final CharGrid grid) { |
| 43 | + return grid.getCells().filter(cell -> isRemovable(grid, cell)).count(); |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public Long solvePart2(final CharGrid grid) { |
| 48 | + final Deque<Cell> queue = new ArrayDeque<>(); |
| 49 | + grid.getCells().filter(cell -> isRemovable(grid, cell)).forEach(queue::add); |
| 50 | + final Set<Cell> seen = new HashSet<>(); |
| 51 | + while (!queue.isEmpty()) { |
| 52 | + final Cell cell = queue.poll(); |
| 53 | + if (seen.contains(cell)) { |
| 54 | + continue; |
| 55 | + } |
| 56 | + seen.add(cell); |
| 57 | + grid.setValue(cell, EMPTY); |
| 58 | + grid.getAllNeighbours(cell).filter(n -> isRemovable(grid, n)).forEach(queue::add); |
| 59 | + } |
| 60 | + return (long) seen.size(); |
| 61 | + } |
| 62 | + |
| 63 | + @Samples({ |
| 64 | + @Sample(method = "part1", input = TEST, expected = "13"), |
| 65 | + @Sample(method = "part2", input = TEST, expected = "43"), |
| 66 | + }) |
| 67 | + public static void main(final String[] args) throws Exception { |
| 68 | + create().run(); |
| 69 | + } |
| 70 | + |
| 71 | + private static final String TEST = |
| 72 | + """ |
| 73 | + ..@@.@@@@. |
| 74 | + @@@.@.@.@@ |
| 75 | + @@@@@.@.@@ |
| 76 | + @.@@@@..@. |
| 77 | + @@.@@@@.@@ |
| 78 | + .@@@@@@@.@ |
| 79 | + .@.@.@.@@@ |
| 80 | + @.@@@.@@@@ |
| 81 | + .@@@@@@@@. |
| 82 | + @.@.@@@.@. |
| 83 | + """; |
| 84 | +} |
0 commit comments