Two-dimensional Dynamic Programming
136 / 170Two-dimensional Dynamic ProgrammingLesson 1 of 11About 61 min
The gentlest two-dimensional state: the answer at a cell, built from the cells that can reach it.
Three tables over the same grid shape, all moving right or down only. cheapest_path returns the minimum total of the values along a route. max_collected returns the maximum total. most_valuable_with_blocks does the same as max_collected except that a cell holding None cannot be entered, and returns -1 when the bottom-right cannot be reached at all.
Tests
grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]print(cheapest_path(grid), max_collected(grid))print(cheapest_path([]), max_collected([]))blocked = [[1, 3, 1], [1, None, 1], [4, 2, 1]]print(most_valuable_with_blocks(blocked), most_valuable_with_blocks([[5]]))print(most_valuable_with_blocks([[1, None], [None, 1]]))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.