3/40
Part 1 of 7 · Four thingsLearn and do

The loops fill row by row, and each cell reads the cell above and the cell to its left

The code is those four lines of thought, in that order:

import math


def most_points(grid):
    rows, cols = len(grid), len(grid[0])
    best = [[-math.inf] * cols for _ in range(rows)]
    # top to bottom
    for r in range(rows):
        # left to right
        for c in range(cols):
            if r == 0 and c == 0:
                best[r][c] = grid[0][0]
                continue
            up = best[r - 1][c] if r > 0 else -math.inf
            left = best[r][c - 1] if c > 0 else -math.inf
            best[r][c] = grid[r][c] + max(up, left)
    return best


grid = [
    [3, 1, 4, 1],
    [1, 5, 9, 2],
    [6, 5, 3, 5],
]
for row in most_points(grid):
    print(row)
[3, 4, 8, 9]
[4, 9, 18, 20]
[10, 15, 21, 26]

The corner holds the answer, 26. Here is the order the loops visit the cells, next to the values they write:

The order the loops fill it, and the values they write
fill order
123456789101112
best
348949182010152126

Each cell reads the cell above and the cell to its left, and both are filled before it.

Every cell a cell reads is already filled. That's the fourth item doing its job.

Every cell took one comparison of two neighbors. So the cost is O(RC)O(RC) time and memory for a grid of RR rows and CC columns.

In the editor, write count_paths(grid): the same four things, counting the paths around walls. It prints the count for a yard with two walls, then for three small grids.