AoC 2022 D8: Treetop Tree House
| Problem statement | Source code | Tags: Memoization
← Previous Back to AoC Index Next →
Part 1
If the grid's side length is , then there are directions to check for visibility. We scan along each direction and count visible trees. To determine the visibility, we need to check all trees before it and see if they are all shorter than the current one—i.e., compare the maximum height of the trees before it. The maximum can be tracked as we scan, so there's no need to scan backwards again.
So prevMax is an accumulator and we store visibleFromLeft for each tree. These two can be done at the same time with mapAccumL and mapAccumR.
I apply this to each row and column (by transposing the grid) and use zipWith to combine each cell with ||. Finally I can count the number of True values.
Part 2
This time, we are not counting visible trees, just finding the distance to the first tree that is taller or equal in height. This can be done with a similar approach, but instead of tracking the maximum height, we track the distance to the last tree of each height.
We can still treat lastIndex as an accumulator, but instead of a single value, we now need to memorize one value per . I use Data.IntMap for this.
Again, we apply these two functions to each row and column and combine the results with zipWith (this time multiplying them). Finally I can find the maximum value.