010203

Advent of Code

2026/3

Foggy Forest

in C#

by encse

The train comes to a stop in a large, misty forest. The Elves are here for petrichor, and they need the highest quality petrichor possible. The best petrichor comes from natural forests, but the Elves are having trouble remembering whether this part of the forest is natural or artificial.

The local afforestation protocols call for trees in artificial forests to be somewhat evenly spaced, causing them to sometimes appear in predictable arrangements. Even if the forest has been left unattended for a while, these predictable arrangements can sometimes still be detected.

Visit the website for the full story and full puzzle description.

namespace AdventOfCode.Y2026.Day03;

[ProblemName("Foggy Forest")]
class Solution : Solver {

    public object PartOne(string input) => TotalSquareCount(input, SquareCount1);

    public object PartTwo(string input) => TotalSquareCount(input, SquareCount2);

    int TotalSquareCount(string input, SquareCount findSquares) {
        var lines = input.Split('\n');
        var ccol = lines[0].Length;
        var crow = lines.Length;
        var res = 0;

        // go over the possible square sizes and count them at each map position
        for (var size = 1; size <= ccol; size++) {
            for (var irow = 0; irow < crow; irow++) {
                for (var icol = 0; icol < ccol; icol++) {
                    res += findSquares(lines, irow, icol, size);
                }
            }
        }
        return res;
    }


    delegate int SquareCount(string[] map, int irow, int icol, int size);

    int SquareCount1(string[] map, int irow, int icol, int size) {
        return HasSquare(map, irow, icol, 0, size) ? 1 : 0;
    }
    int SquareCount2(string[] map, int irow, int icol, int size) {
        // similar to SquareCount1, but also checks for rotated squares
        // so that the direction vector has length: drow + dcol == size.
        var res = 0;
        for (var drow = 0; drow < size; drow++) {
            if (HasSquare(map, irow, icol, drow, size - drow)) {
                res++;
            }
        }
        return res;
    }

    bool HasSquare(string[] map, int irow, int icol, int drow, int dcol) {
        // steps over the 4 corners while turning the direction
        // vector 90 degrees in each step.
        for (var i = 0; i < 4; i++) {
            if (!HasTree(map, irow, icol)) {
                return false;
            }
            (irow, icol) = (irow + drow, icol + dcol);
            (drow, dcol) = (dcol, -drow);
        }
        return true;
    }

    bool HasTree(string[] map, int irow, int icol) {
        if (icol < 0 || icol >= map[0].Length || irow < 0 || irow >= map.Length) {
            return false;
        }
        return map[irow][icol] == '#';
    }
}

Please ☆ my repo if you like it!

© 2026 | Advent of Code is a registered trademark in the US | Images provided by Bing and Nano Banana