Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Count paths modulo 10⁹ + 7 from the top-left to the bottom-right of a 3 × 3 board whose centre is blocked, moving right, down or diagonally down-right.

Problem: Count paths modulo 10⁹ + 7 from the top-left to the bottom-right of a 3 × 3 board whose centre is blocked, moving right, down or diagonally down-right.
M = 10**9 + 7
g = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
dp = [[0] * 3 for _ in range(3)]; dp[0][0] = 1
for r in range(3):
    for c in range(3):
        if g[r][c] or (r, c) == (0, 0): continue
        dp[r][c] = ((dp[r-1][c] if r else 0) + (dp[r][c-1] if c else 0) + (dp[r-1][c-1] if r and c else 0)) % M
print(dp[2][2], dp[1][2])
What is printed?
  1. A. 6 2
  2. B. 4 2
  3. C. 13 3
  4. D. 2 1

Correct answer: B. 4 2

dp[r][c] = paths from the top, the left and the top-left diagonal; a blocked cell stays 0. Row 0 and column 0 have 1 path each; (1, 2) gets 1 (from above) + 0 (blocked centre) + 1 (diagonal from (0, 1)) = 2, and symmetrically (2, 1) = 2; the corner gets 2 + 2 + 0 = 4. Without the block the count would be 13 (a Delannoy number). O(R·C).

More Coding Interview Problems questions

Exams that ask this topic