Advent of Code 2026 Day 3: Foggy Forest
from advent import combinations, grid_to_dict, parse
map = grid_to_dict(parse(3), lambda c: c == '#')
def has_square(src, dst, aligned):
delta = dst - src
if not (delta.real == 0 if aligned else delta.real > 0):
return False
flipped = complex(delta.imag, -delta.real)
return (src + flipped) in map and (dst + flipped) in map
def solve(aligned=True):
return sum(
1 for src, dst in combinations(map.keys(), 2) if has_square(src, dst, aligned)
)
assert solve() == 329
assert solve(aligned=False) == 1622
Problem
We're given a map that is a two dimensional grid where # characters indicate trees. Our goal for both parts is to count how many times four trees form four corners of a square. For part one the squares are grid-aligned, and for part two the squares do not need to be aligned.
Input Parsing
My advent.py module has a grid_to_dict() function because parsing grids is very common in Advent of Code. It parses the input file and creates a Python dictionary with the coordinates (as complex numbers) as keys. grid_to_dict() is extremely flexible, with the ability to filter and transform both rows and individual cells, but our needs today are fairly simple, so we just make use of the filter to grab only trees.
This input:
results in:
Solution
Our approach is somewhat naive, as I'm emphasizing simplicity and readability. We'll form the 2-combinations of all trees, and determine if there is a square associated with them, and sum the total.
The complex numbers we use for coordinates are formed with the real part indicating the row, and the imaginary part indicating the column, e.g. complex(row, col).
The meat of the solution is in the has_square() predicate. It accepts 3 parameters: coordinates of the "source" tree, coordinates of the "destination" tree, and a boolean indicating whether the square needs to be aligned.
First, we'll compute a vector from the source tree to the destination tree:
Next, we'll filter out vectors to avoid computing the same square more than once. In the aligned case, we only want horizontal vectors pointing to the right. In the non-aligned case, we only want vectors pointing downward:
Now that we have the right vectors, we compute a perpendicular vector by negating the row, and swapping row and column:
All that is left to do is to add this perpendicular vector to both source tree and destination tree, and see if they both exist:
With the main predicate in place, we only need to create the 2-combinations, and sum everything up: