Advent of Code 2024 - Day 12Garden Groups
| Problem statement | Source code | Tags: Geometry
This problem pays tribute to 2023 day 5 and 2023 day 21.
Part 1
This map is almost usable as-is, but there are different regions marked by the same letter. Therefore we do a flood fill for each letter, and assign a unique ID to each region.
Now for part 1, we can just go through each cell. Every cell contributes 1 to its area, and contributes 1 to the perimeter if it's on the edge; i.e., it has a neighbor that's not the same region.
Part 2
Now we need the number of edges of each region, so not all edge cells are counted. A shape's number of edges is the number of its corners, but we need to count both convex and reflex corners, which makes it a bit more involved. Let's think about the 3x3 neighborhood of a cell:
There are 8 corners that c can possibly be: a convex corner in top-left, top-right, bottom-left, or bottom-right; and a reflex corner in the same directions. If it's a convex corner in the top-left, that means that n2 and n4 are different from c. (n1 might not be; for example, in the 368 example, there are two touching A corners in the center of the board.) If it's a reflex corner in the top-left, that means that n1 is different from c, but n2 and n4 are the same as c.
A cell can simultaneously be a corner in multiple directions. For example, a lone cell is a convex corner in all four directions. However, a cell cannot simultaneously be a convex corner and a reflex corner in the same direction.
I do this counting for each cell.
corners is equivalent to the number of edges, so the final answer is the sum of areas.(i) * corners.(i) for all i.