Data Structures & AlgorithmsHardTCS NQT · Accenture

Problem: Count right/down paths from the top-left to the bottom-right of the 3x3 grid below, where '#' is blocked. The code returns the count of reachable paths.

Problem: Count right/down paths from the top-left to the bottom-right of the 3x3 grid below, where '#' is blocked. The code returns the count of reachable paths.
def paths(g):
    n, m = len(g), len(g[0])
    dp = [[0] * m for _ in range(n)]
    dp[0][0] = 1
    for i in range(n):
        for j in range(m):
            if g[i][j] == '#':
                dp[i][j] = 0
                continue
            if i:
                dp[i][j] += dp[i - 1][j]
            if j:
                dp[i][j] += dp[i][j - 1]
    return dp[-1][-1]
print(paths(['...', '.#.', '...']))
What is printed?
  1. A. 2
  2. B. 4
  3. C. 6
  4. D. 3

Correct answer: A. 2

There are C(4,2) = 6 monotone paths, and 4 of them pass through the blocked centre, leaving 2. The DP sums paths from above and left while skipping blocked cells.

More Coding Interview Problems questions

Exams that ask this topic