ProgrammingHardCodeforces-style · placement coding round

What is printed?

What is printed?
def min_path(g):
    dp = [0] * len(g[0])
    for i, row in enumerate(g):
        for j, v in enumerate(row):
            if i == 0 and j == 0:
                dp[j] = v
            elif i == 0:
                dp[j] = dp[j - 1] + v
            elif j == 0:
                dp[j] = dp[j] + v
            else:
                dp[j] = min(dp[j], dp[j - 1]) + v
    return dp[-1]
print(min_path([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))
  1. A. 7
  2. B. 9
  3. C. 12
  4. D. 21

Correct answer: A. 7

The rolling dp keeps the cheapest cost to each column: the route 1 → 3 → 1 → 1 → 1 costs 7. Greedily stepping to the smaller neighbour costs 9, the most expensive right/down route is 12, and 21 is the sum of the whole grid.

More Python Programming questions

Exams that ask this topic