Predict the output
What does this print?
import math
grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
row = [math.inf] * 3
row[0] = 0
for cells in grid:
for c, cost in enumerate(cells):
left = row[c - 1] if c else math.inf
row[c] = cost + min(row[c], left)
print(row)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [6, 8, 7]
Right: the bottom-right cell is 7 via 1, 3, 1, 1, 1, and the first column sums to 6.
The rolling row holds the cheapest cost into each column of the current row, so its last entry is the answer.
Why not the others?
- B [7, 8, 7]. The bottom-left cell has only one way in: 1 + 1 + 4 = 6.
- C [6, 9, 8]. Each cell takes the cheaper of above and left.