Data Structures & AlgorithmsHardICPC regional · grid DP

Problem: How many monotone lattice paths from (0,0) to (2,2) exist on a 3 x 3 grid if the moves are right, down or diagonal (down-right)? Run the DP.

Problem: How many monotone lattice paths from (0,0) to (2,2) exist on a 3 x 3 grid if the moves are right, down or diagonal (down-right)? Run the DP.
dp = [[0] * 3 for _ in range(3)]
for i in range(3):
    for j in range(3):
        if i == 0 and j == 0:
            dp[i][j] = 1
            continue
        v = 0
        if i:
            v += dp[i - 1][j]
        if j:
            v += dp[i][j - 1]
        if i and j:
            v += dp[i - 1][j - 1]
        dp[i][j] = v
print(dp[2][2])
What is printed?
  1. A. 6
  2. B. 12
  3. C. 13
  4. D. 20

Correct answer: C. 13

With diagonal moves allowed, the count is the Delannoy number D(2,2) = 13. Ignoring the diagonal move gives the trap 6.

More Coding Interview Problems questions

Exams that ask this topic