KatInterview

Grid Traversal with Sequential Waypoints

Dynamic ProgrammingAuto-graded · 26 test cases
MediumAuto-gradedDynamic Programminggriddpspace-optimization

Last updated

Tests dynamic programming on a grid with diagonal moves, tracking reachable states column-by-column while enforcing waypoint visitation order.

You have an n × m grid where rows are indexed 0 to n - 1 from top to bottom and columns are indexed 0 to m - 1 from left to right.

A valid path begins at cell (n - 1, 0) in the bottom-left corner and ends at cell (n - 1, m - 1) in the bottom-right corner. From any cell (r, c), you can move to one of three adjacent cells in the next column:

  • (r - 1, c + 1) — diagonal up-right
  • (r, c + 1) — straight right
  • (r + 1, c + 1) — diagonal down-right

All moves must remain within grid boundaries.

You are given a list of waypoint cells that must be visited in the specified order. Calculate how many valid paths satisfy this constraint, and return the result modulo 1_000_000_007.

Parameters

  • n (int): number of rows in the grid
  • m (int): number of columns in the grid
  • waypoints (list of [row, col] pairs): cells that must be visited in the given sequence

Return Value

An integer representing the count of valid paths modulo 1_000_000_007.

Rules

  • Each move advances exactly one column to the right, so every path visits exactly one cell per column.
  • Waypoint i must be visited before waypoint i + 1 for all valid indices.
  • If no valid path exists that satisfies all waypoint constraints, return 0.
  • When m = 1, the start and end are identical, and the only valid path contains just that single cell.

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ 1000
  • 0 ≤ len(waypoints) ≤ 1000
  • Each waypoint [r, c] satisfies 0 ≤ r < n and 0 ≤ c < m
  • All waypoint cells are distinct
  • The exact path count can be extremely large (hundreds of digits), which is why the modulo operation is required

Examples

Example 1

Input: count_grid_paths(3, 4, [])

Output: 4

Example 2

Input: count_grid_paths(3, 4, [[1, 1], [2, 2]])

Output: 1

Example 3

Input: count_grid_paths(3, 4, [[2, 2], [1, 1]])

Output: 0

Hints

Hint 1

Since each move goes exactly one column to the right, any valid path visits exactly one cell per column. What does this tell you about waypoint ordering?

Hint 2

Use dynamic programming column-by-column. Track how many ways there are to reach each row in the current column, then transition to the next column based on allowed moves.

Hint 3

Not all rows in a column can be part of a complete path. A cell can only be reached if there are enough columns to climb from the start, and enough columns remaining to descend back to the target end row.