Count Paths with Target Sum
Count distinct top-left to bottom-right paths through a 5×5 grid whose collected values sum to exactly 46 (right or down moves only).
A1:E5 is a 5×5 grid of positive integers. A walker enters at A1, moves
only right or down, and collects the value of every cell it visits
(start and end included). Each path produces a single sum.
Return the count of distinct paths whose collected sum equals exactly 46.
There are C(8, 4) = 70 paths in total. Their sums distribute over a wide range, with the target value sitting in the middle of the distribution — the formula’s job is to enumerate, accumulate per branch, and tally hits at the goal.
Input
Range A1:E5
| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | 5 | 6 | 4 | 4 | 4 |
| 2 | 2 | 5 | 8 | 9 | 4 |
| 3 | 3 | 9 | 9 | 1 | 5 |
| 4 | 1 | 8 | 3 | 4 | 9 |
| 5 | 7 | 3 | 6 | 6 | 2 |
Hint
Branching recursion that carries a running total as a recursion argument. At the goal cell, return 1 if the total matches the target, else 0. Otherwise recurse down + right and SUM the results.
Solution
=LET(
target, 46,
tbl, A1:E5,
ros, ROWS(tbl),
cols, COLUMNS(tbl),
fx, LAMBDA(me, ro, co, total,
IF(OR(ro>ros, co>cols),
0,
LET(
new_total, total + INDEX(tbl, ro, co),
IF(AND(ro=ros, co=cols),
IF(new_total=target, 1, 0),
me(me, ro+1, co, new_total) + me(me, ro, co+1, new_total)
)
)
)
),
fx(fx, 1, 1, 0)
)