KatInterview

Count Paths Through a Grid with Blocked Cells

Dynamic ProgrammingAuto-graded · 17 test cases
EasyAuto-gradedDynamic Programmingdynamic programminggridpaths

Last updated

Tests whether a candidate can apply bottom-up DP on a 2-D grid to count reachable paths from top-left to bottom-right while respecting blocked cells.

Count Paths Through a Grid with Blocked Cells

You are given a rectangular grid of rows rows and cols columns. Each cell is either open (0) or blocked (1). Starting from the top-left cell (0, 0), you want to reach the bottom-right cell (rows-1, cols-1) by moving only right or down at each step.

Write a function that returns the number of distinct paths from the top-left to the bottom-right corner.

  • If the start cell (0, 0) or the end cell (rows-1, cols-1) is blocked, return 0.
  • A path is invalid if it passes through any blocked cell.
  • If rows == 0 or cols == 0, return 0.

The answer is guaranteed to fit in a 64-bit signed integer for all provided inputs.

Constraints

  • 0 <= rows, cols <= 100
  • Each cell value is either 0 (open) or 1 (blocked)
  • grid is a list of rows lists, each of length cols
  • Moving diagonally is not allowed; only right or down

Examples

Example 1

Input: count_grid_paths([[0, 0, 0], [0, 0, 0], [0, 0, 0]])

Output: 6

Example 2

Input: count_grid_paths([[0, 1, 0], [0, 0, 0], [0, 0, 0]])

Output: 3

Example 3

Input: count_grid_paths([[0, 0], [1, 0]])

Output: 1

Hints

Hint 1

Build a 2-D DP table where dp[r][c] is the number of ways to reach cell (r, c). Start from (0,0) and fill left-to-right, top-to-bottom.

Hint 2

For each open cell, dp[r][c] = dp[r-1][c] + dp[r][c-1]. For a blocked cell, dp[r][c] = 0 regardless of its neighbours.

Hint 3

Handle the first row and first column carefully: once a blocked cell is encountered, all cells beyond it in that row or column are also unreachable.