Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Count paths from the top-left to the bottom-right of a grid moving only right or down, where 1 marks a blocked cell.

Problem: Count paths from the top-left to the bottom-right of a grid moving only right or down, where 1 marks a blocked cell.
def paths(g):
    R, C = len(g), len(g[0])
    dp = [0] * C; dp[0] = 1
    for r in range(R):
        for c in range(C):
            if g[r][c]: dp[c] = 0
            elif c: dp[c] += dp[c - 1]
    return dp[-1]
print(paths([[0, 0, 0], [0, 1, 0], [0, 0, 0]]), paths([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]))
What is printed?
  1. A. 2 10
  2. B. 6 10
  3. C. 2 20
  4. D. 3 10

Correct answer: A. 2 10

dp[c] holds paths to the current cell: from above (old dp[c]) plus from the left (dp[c − 1]). The centre block leaves only the two border routes. A free 3 × 4 grid has C(5, 2) = 10 paths. O(R·C) time, O(C) space.

More Coding Interview Problems questions

Exams that ask this topic