KatInterview

Count Lattice Paths Through Forbidden Checkpoints

Math & Bit ManipulationAuto-graded · 17 test cases
MediumAuto-gradedMath & Bit Manipulationcombinatoricsmathdynamic programming

Last updated

Tests combinatorial counting of grid paths using inclusion-exclusion and binomial coefficients, requiring precise arithmetic on a bounded lattice.

Count Lattice Paths Through Forbidden Checkpoints

You are navigating an m × n grid from the top-left corner (0, 0) to the bottom-right corner (m-1, n-1). At each step you may move right or down only.

A set of cells is marked as forbidden — you must not step on any of them. Count the number of distinct paths from (0, 0) to (m-1, n-1) that avoid every forbidden cell, modulo 10^9 + 7.

The forbidden list may be empty. If (0, 0) or (m-1, n-1) is forbidden, or if no valid path exists, return 0.

Constraints

  • 1 ≤ m, n ≤ 500
  • 0 ≤ len(forbidden) ≤ min(m * n, 2000)
  • Each element of forbidden is a list [r, c] with 0 ≤ r < m and 0 ≤ c < n.
  • Duplicate entries in forbidden are possible; treat them as a single blocked cell.
  • The grid may be a single cell (m = n = 1) with no forbidden cells — in that case there is exactly 1 path (standing still).

Examples

Example 1

Input: count_lattice_paths(3, 3, [])

Output: 6

Example 2

Input: count_lattice_paths(3, 3, [[1, 1]])

Output: 2

Example 3

Input: count_lattice_paths(1, 1, [])

Output: 1

Hints

Hint 1

Build a 2-D DP table where dp[r][c] is the number of valid paths reaching cell (r, c). Initialize dp[0][0] = 1, mark forbidden cells as 0, and fill row by row.

Hint 2

When a cell is forbidden, force its DP value to 0 so it contributes nothing to cells that follow it.

Hint 3

For large grids the table can reach 500×500 = 250,000 cells; a straightforward O(m·n) DP pass fills this well within time limits. Remember to take every addition modulo 10^9 + 7.