Foggy Forest
2026-12-04Original PuzzlePart 1
Ah, AoC and grid puzzles; a classic pairing. So classic that I’ve got a whole helper method for parsing grids. It parses a file into a dict with (row, col) keys and the character as the value.
It can ignore characters, which is useful if we are only worried about a specific thing (such as today’s trees). From there, tasks like iterating and checking presence are fast and simple dict operations! …which is extra useful today, when we have to look at each point tree and see what other trees line up.
A square is just 4 trees at fixed distances from each other. So if we look at each tree and treat as the top-left corner of a potential square, then we know exactly where the other trees would need to be. If we find all 3, it’s a bingo! Squares can be any size, so we’ll need to check each size up to the size of the forest.
Let’s see how that looks:
class Solution(StrSplitSolution): def part_1(self) -> int: forest = parse_forest(self.input, ignore_chars=".") # custom helper, see above # => { (0, 0): '#', (0, 4): '#', (2, 2): '#', ... }
total = 0 assert len(self.input) == len(self.input[0]), "not a square forest" forest_size = len(self.input)
for row, col in forest: # check every possible square size that fits in the forest for size in range(1, forest_size): if ( # bottom left (row + size, col) not in forest # top right or (row, col + size) not in forest # bottom right or (row + size, col + size) not in forest ): continue
# if we didn't bail, it's a square! total += 1
return totalThere’s some extra checking to get the grid size (and ensure that len(self.input) doesn’t give a different answer than len(self.input([0])) but it’s a pretty straightforward approach.
I also like that I don’t have to track the trees of found squares. Since we treat each element in forest as the top left corner only, there’s no chance of finding a duplicate. Pretty slick!
Part 2
It feels like the approach from part 1 will work again here, we just need to update the way we look for our other 3 corners. We’ve established above that I know what a square is. But reading part 2 made me come to terms with the fact that I’m not positive I know what a rotated square is. Let’s figure it out!
In a square, there are 2 rows and 2 columns with 2 trees each. We could rely on having a tree in the top left. But when you’re rotating a square, do you still have that reliable anchor?
Turns out yes! When you’re rotating a square, there will only ever be a single tree in the topmost row. If there were two trees, then you’re back to an un-rotated square. And if you have 3 trees, then something is horribly wrong with your square.
Now we need some new equations to find corners- it’s no longer as simple as adding to either the row or column.
To figure out our new arithmetic, I studied the pattern that the trees rotated in. This was the most helpful example (with our anchor tree marked as $):
$...#...............#...#
.$.......#.....#.......#.
..$.......#...#.......#..
...$.#.............#.#...
#...$...............#...#Each rotation, the anchor gets one column closer to the rightmost tree as it moves one row farther away. The left is the opposite (fewer rows, more columns). Once we’ve rotated size times, we’re back to a normal square, but our anchor is in the top right (a case we don’t need to consider, since our part 1 code will catch it).
Before we write anything new, let’s restructure our code a bit. We’ll move the logic into a function so both parts of the solution can use it:
class Solution(StrSplitSolution): def part_1(self) -> int: def _solve(self, /, include_diagonals=False) -> int: forest = parse_forest(self.input, ignore_chars=".")
total = 0 assert len(self.input) == len(self.input[0]), "not a square forest" forest_size = len(self.input)
for row, col in forest: # check every possible square size that fits in the forest for size in range(1, forest_size): if ( # bottom left (row + size, col) not in forest (row + size, col) in forest # top right or (row, col + size) not in forest and (row, col + size) in forest # bottom right or (row + size, col + size) not in forest and (row + size, col + size) in forest ): continue total += 1
return totalThe
/argument means that subsequent arguments must be passed by name. This means callers need to useself._solve(include_diagnoals=True)instead ofself._solve(True), which is dramatically more readable. Unnamed bool arguments is sort of an antipattern because of how indecipherable there are at callsites.
We’ve inverted our conditionals since we don’t want to bail early just because we didn’t find a flag square.
Next the diagonals. We have to try each offset up to our size since we don’t know which position the square is in. The math for each point is the same though:
class Solution(StrSplitSolution): def _solve(self, /, include_diagonals=False) -> int: ...
for row, col in forest: for size in range(1, forest_size): ...
if include_diagonals: for offset in range(1, size): if ( # left (row + size - offset, col - offset) in forest # right and (row + offset, col + size - offset) in forest # bottom # ... TBD ): total += 1The math for each tree corresopnds to the flat version above, but with the inclusion of the offset. I got these by literally counting points in those examples above and seeing how an increasing rotational offset affected the row and col of the other trees.
The bottom tree is the bugbear. Its row value is easy: it’s just row + size. Just like our anchor tree, the tree formally known as bottom-right never leaves its original row bottom row and the size of the square hasn’t changed, so neither does the bottom tree’s row.
The col is the tricky bit. In our sequence above, the top and bottom trees are 4, 2, 0, 2, and 4 columns apart. The fact that we’re not just stepping by 1 should clue into the fact that we can’t just add an offset. And, when we’re halfway through our rotation, they’re on the same column. That smells like multiplication!
It took some trial and error, but I figured out that bottom tree moves by a step of size - offset * 2. The * 2 represents how our top and bottom tree are each moving along the same axis, so the distance jumps by 2 every time. And when offset is 2 (halfway through our rotation for a size-4 square), we get 4 - 4, which put them in the same column.
Plug that in and wire up the parts and we’ve got our answer!
class Solution(StrSplitSolution): def _solve(self, /, include_diagonals=False) -> int: ...
for row, col in forest: for size in range(1, forest_size): ...
if include_diagonals: for offset in range(1, size): if ( # left (row + size - offset, col - offset) in forest # right and (row + offset, col + size - offset) in forest # bottom and (row + size, col + (size - offset * 2)) in forest ): total += 1
def part_1(self) -> int: return self._solve()
def part_2(self) -> int: return self._solve(include_diagonals=True)A final optimization
This is the first puzzle part so far that runs in perceptable time (around .7 seconds, e.g. feels longer than ~instant on my machine). I had a feeling we were checking a larger range than we needed to (which is extra costlyin a nested loop). Put another way: is there any point in either of those loops where we know we can’t find a valid square?
Yes! Our very top loop checks every size from 1 to the whole width/height of the forest. But if we find a tree halflway through the forest, we only need to check range(1, size // 2), which will save us a lot of loops. Now the question becomes “how early can we bail?”.
If we only had to worry about part 1, then we could stop as soon as either row + size or col + size was greater than forest_size. But part 2 subtracts from size a lot, so a size that exceeds the bounds in part 1 could still find something in part 2. Except! Finding the bottom tree in part 2 has us do a row + size. As a result, no size that’s bigger than forest_size - row could find a tree in either part:
class Solution(StrSplitSolution): def _solve(self, /, include_diagonals=False) -> int: ...
for row, col in forest: for size in range(1, forest_size): for size in range(1, forest_size - row):That gets my runtime down to ~.23 seconds, which is just at the bottom range of perceptible. Good enough for today!