Dynamic Programming21 sections · 916 units
Open in Course

Grid 1 - Implementation

The code

Here is the implementation for Grid 1 (AtCoder DP-HH):

MOD := 1000000007
Input: H, W, grid[1..H][1..W]

dp := 2D array of size H × W, all set to 0

if grid[1][1] = '.' then
    dp[1][1] := 1

for i from 1 to H
    for j from 1 to W
        if grid[i][j] = '#' then
            dp[i][j] := 0
        else
            if i > 1 then
                dp[i][j] := (dp[i][j] + dp[i - 1][j]) mod MOD
            if j > 1 then
                dp[i][j] := (dp[i][j] + dp[i][j - 1]) mod MOD

return dp[H][W]

You fill the grid row by row, left to right. For each empty cell, add the paths from above and from the left. Wall cells stay at 00, blocking all paths through them. The mod keeps numbers from overflowing. Trace a small 3×33 \times 3 grid with one wall to see how blocked cells cut off entire regions.

Time complexity: O(HW)O(H \cdot W).

Space complexity: O(HW)O(H \cdot W), reducible to O(W)O(W) by keeping only the current and previous rows.