KatInterview

Count Lattice Paths Avoiding Forbidden Cells

Math & Bit ManipulationAuto-graded · 18 test cases
HardAuto-gradedMath & Bit Manipulationcombinatoricsdynamic programmingmath

Last updated

Tests combinatorics by counting monotone lattice paths from (0,0) to (m,n) that avoid a given set of forbidden grid cells, using inclusion-exclusion over path prefixes.

Count Lattice Paths Avoiding Forbidden Cells

You are standing at cell (0, 0) on an (m+1) × (n+1) integer grid (columns 0..m, rows 0..n). You want to reach cell (m, n) by taking only right steps (column + 1) or up steps (row + 1).

Some cells are forbidden — you may not step on any of them.

Return the number of valid monotone paths from (0, 0) to (m, n) that avoid every forbidden cell, modulo 10^9 + 7.

  • (0, 0) and (m, n) are guaranteed not to be forbidden.
  • A path visits exactly m + n + 1 cells (including start and end).
  • Any cell (c, r) with 0 ≤ c ≤ m, 0 ≤ r ≤ n may be forbidden.

Approach hint

The number of unrestricted monotone paths from (c1, r1) to (c2, r2) (with c2 ≥ c1, r2 ≥ r1) is the binomial coefficient C((c2-c1) + (r2-r1), c2-c1).

Use dynamic programming over the forbidden cells (sorted topologically along paths) combined with the above formula to subtract paths that pass through at least one forbidden cell.

Constraints

  • 1 ≤ m, n ≤ 500
  • 0 ≤ len(forbidden) ≤ 200
  • Each forbidden cell is given as [col, row] with 0 ≤ col ≤ m, 0 ≤ row ≤ n.
  • No duplicate forbidden cells.
  • (0, 0) and (m, n) are never forbidden.
  • Return the answer modulo 10^9 + 7.

Examples

Example 1

Input: count_lattice_paths(3, 3, [])

Output: 20

Example 2

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

Output: 8

Example 3

Input: count_lattice_paths(2, 2, [[1, 0], [0, 1]])

Output: 0

Hints

Hint 1

Sort the forbidden cells so that cell A comes before cell B whenever a monotone path could visit A before B (i.e., A.col ≤ B.col and A.row ≤ B.row). A topological order by (col+row, col) works.

Hint 2

Let bad[i] = number of paths from (0,0) to forbidden[i] that avoid all forbidden cells with smaller index. Use the formula: bad[i] = C(ci+ri, ci) - sum over all j < i reachable-from-j-to-i of bad[j] * C((ci-cj)+(ri-rj), ci-cj).

Hint 3

The final answer is C(m+n, m) minus the sum of bad[i] * C((m-ci)+(n-ri), m-ci) over all forbidden cells i, all computed modulo 10^9+7.