progress

~/problems / 2-D dynamic programming / Grid DP

Mushroom walks with an exact haul

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min

A forager crosses a field of equal-length strings: "." is grass, "m" a mushroom, "#" a boulder. She goes from the top-left cell to the bottom-right, moving only right or down and never onto a boulder, picking the mushroom on every "m" she steps on (start and finish included).

Implement count_walks(grid: list[str], k: int) -> int: the number of routes that pick exactly k mushrooms.

count_walks([
    "m..",
    ".m.",
    "..m",
], 2)  # 2   all 6 routes pick both corner mushrooms; the 4 that pass the centre
       #     pick 3, so 2 routes pick exactly 2

count_walks(["..",
             "m."], 0)  # 1   right, then down

If the start or finish is a boulder, the answer is 0. Grids are up to 40 x 40, k <= 80; return the exact (possibly huge) count.

⭐ Bonus: a speed test on a 40 x 40 field earns a star with a DP over (row, col, mushrooms so far). Listing every route is hopeless there.

Show hint

ways[r][c][j] = routes to (r, c) with exactly j mushrooms so far: the sum of ways[r-1][c][j - here] and ways[r][c-1][j - here], where here is 1 on a mushroom.

Topic: Grid DP. dp[r][c] from neighbours; add a dimension for extra state (jumps left).

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc