progress

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

Can you reach the corner?

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

easy basics ~10 min

A grid is given as a list of equal-length strings: "." is open and "#" is a rock. You start in the top-left cell and want to reach the bottom-right cell, moving only right or down, and never onto a rock.

Implement can_reach(grid: list[str]) -> bool: is there at least one route?

can_reach(["...",
           ".#.",
           "..."])   # True    around the rock either way
can_reach([".#",
           "#."])    # False   both first moves hit a rock
can_reach(["."])     # True    you're already there

If the start or the finish is a rock, the answer is False. Constraints: grids are 1 to 100 cells on each side.

Show hint

ok[r][c] is True when the cell is open and you can reach the cell above it or the cell to its left (cells outside the grid count as False). Fill it row by row from ok[0][0].

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