Grid Traversal with Sequential Waypoints
Dynamic ProgrammingAuto-graded · 26 test casesLast 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 gridm(int): number of columns in the gridwaypoints(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
imust be visited before waypointi + 1for 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 ≤ 10001 ≤ m ≤ 10000 ≤ len(waypoints) ≤ 1000- Each waypoint
[r, c]satisfies0 ≤ r < nand0 ≤ 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since every move advances exactly one column, a valid path visits precisely one cell in each column. This observation leads to two key insights:
-
Waypoint ordering translates to column ordering: For waypoints to be visited in sequence, their column indices must be strictly increasing. If two waypoints share a column or a later waypoint has an earlier column, no valid path exists.
-
Column-by-column dynamic programming: We can build paths incrementally from left to right. For each column, track the number of ways to reach each row, then transition to the next column based on the three allowed moves.
We optimize space by working with "height above the bottom row" instead of absolute row indices. At column c, a cell can only participate in a complete path if:
- It's reachable from the start: height ≤
c - It can reach the end: height ≤
m - 1 - c - It's within the grid: height ≤
n - 1
This bounds our DP state to O(min(n, m)) entries per column.
Why It Works
We maintain the invariant that after processing column c, cur[j] equals the number of valid path prefixes ending at height j in column c, satisfying all waypoint constraints up to that column.
For the transition, paths reaching height j in column c must come from height j-1, j, or j+1 in column c-1 (corresponding to the three move types). Since these are mutually exclusive, we sum their counts.
When a waypoint appears, we zero out all rows except the required one, ensuring only paths through that waypoint are counted.
Complexity
- Time: O(K + m · min(n, m)) where K is the number of waypoints. Validating waypoints takes O(K), and each of m columns requires O(min(n, m)) work.
- Space: O(min(n, m)) for the rolling DP array, plus O(K) for the waypoint map.
Solution
def count_grid_paths(n: int, m: int, waypoints: list[list[int]]) -> int:
MOD = 1_000_000_007
# Build waypoint map and verify column ordering
waypoint_map = {}
previous_column = -1
for row, col in waypoints:
if col <= previous_column:
return 0
previous_column = col
waypoint_map[col] = row
bottom_row = n - 1
# Verify start and end waypoints if they exist
if 0 in waypoint_map and waypoint_map[0] != bottom_row:
return 0
if m - 1 in waypoint_map and waypoint_map[m - 1] != bottom_row:
return 0
# DP state: cur[height] = number of ways to reach (bottom_row - height) in current column
cur = [1]
for col in range(1, m):
# Maximum reachable height at this column
max_height = min(col, m - 1 - col, n - 1)
prev_len = len(cur)
new = [0] * (max_height + 1)
for height in range(max_height + 1):
total = 0
# From same height in previous column (straight right)
if height < prev_len:
total += cur[height]
# From one height below in previous column (diagonal up-right)
if height - 1 >= 0 and height - 1 < prev_len:
total += cur[height - 1]
# From one height above in previous column (diagonal down-right)
if height + 1 < prev_len:
total += cur[height + 1]
new[height] = total % MOD
# Apply waypoint constraint if this column has one
if col in waypoint_map:
required_height = bottom_row - waypoint_map[col]
if required_height > max_height:
return 0
kept_value = new[required_height]
new = [0] * (max_height + 1)
new[required_height] = kept_value
cur = new
return cur[0] % MOD