ProgrammingHardTCS NQT · Wipro pattern

What is printed?

What is printed?
def paths(g):
    R, C = len(g), len(g[0])
    dp = [[0] * C for _ in range(R)]
    dp[0][0] = 0 if g[0][0] else 1
    for r in range(R):
        for c in range(C):
            if g[r][c]:
                dp[r][c] = 0
            elif r == 0 and c == 0:
                continue
            else:
                dp[r][c] = (dp[r-1][c] if r else 0) + (dp[r][c-1] if c else 0)
    return dp[-1][-1]
print(paths([[0, 0, 0], [0, 1, 0], [0, 0, 0]]), paths([[0, 1], [0, 0]]))
  1. A. 2 2
  2. B. 3 1
  3. C. 2 1
  4. D. 1 1

Correct answer: C. 2 1

The DP counts right-or-down paths that avoid blocked cells. The 3x3 grid with a blocked centre has 2 paths, and the 2x2 grid with a blocked top-right cell has 1.

More Python Programming questions

Exams that ask this topic