#3797

Count Routes to Climb a Rectangular Grid

Hard
ArrayDynamic ProgrammingMatrixPrefix SumDynamic ProgrammingGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m * d)
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m * d)Space O(n * m)

We can use dynamic programming to efficiently count paths by storing results of subproblems. This avoids redundant calculations and allows us to build up the solution from the bottom row to the top.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table where dp[r][c][0] counts paths from below and dp[r][c][1] counts paths staying on the same row.
  2. 2Step 2: Iterate from the bottom row to the top, updating the DP table based on valid moves within distance d.
  3. 3Step 3: Sum paths from the top row to get the total count.
solution.py14 lines
1def countRoutes(grid, d):
2    n, m = len(grid), len(grid[0])
3    dp = [[[0, 0] for _ in range(m)] for _ in range(n)]
4    for c in range(m):
5        if grid[n-1][c] == '.': dp[n-1][c][0] = 1
6    for r in range(n-2, -1, -1):
7        for c in range(m):
8            if grid[r][c] == '.':
9                for nc in range(max(0, c-d), min(m, c+d+1)):
10                    if grid[r+1][nc] == '.':
11                        dp[r][c][0] += dp[r+1][nc][0]
12                        dp[r][c][1] += dp[r+1][nc][0]
13                dp[r][c][0] += dp[r][c][1]
14    return sum(dp[0][c][0] for c in range(m))

Complexity note: The complexity is driven by the need to fill the DP table, iterating through rows, columns, and possible moves within distance d.

  • 1Dynamic programming helps avoid redundant calculations.
  • 2Understanding movement constraints is crucial for path counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.