LeetCode #3797 — HARD

Count Routes to Climb a Rectangular Grid

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given a string array grid of size n, where each string grid[i] has length m. The character grid[i][j] is one of the following symbols:

  • '.': The cell is available.
  • '#': The cell is blocked.

You want to count the number of different routes to climb grid. Each route must start from any cell in the bottom row (row n - 1) and end in the top row (row 0).

However, there are some constraints on the route.

  • You can only move from one available cell to another available cell.
  • The Euclidean distance of each move is at most d, where d is an integer parameter given to you. The Euclidean distance between two cells (r1, c1), (r2, c2) is sqrt((r1 - r2)2 + (c1 - c2)2).
  • Each move either stays on the same row or moves to the row directly above (from row r to r - 1).
  • You cannot stay on the same row for two consecutive turns. If you stay on the same row in a move (and this move is not the last move), your next move must go to the row above.

Return an integer denoting the number of such routes. Since the answer may be very large, return it modulo 109 + 7.

Example 1:

Input: grid = ["..","#."], d = 1

Output: 2

Explanation:

We label the cells we visit in the routes sequentially, starting from 1. The two routes are:

.2
#1
32
#1

We can move from the cell (1, 1) to the cell (0, 1) because the Euclidean distance is sqrt((1 - 0)2 + (1 - 1)2) = sqrt(1) <= d.

However, we cannot move from the cell (1, 1) to the cell (0, 0) because the Euclidean distance is sqrt((1 - 0)2 + (1 - 0)2) = sqrt(2) > d.

Example 2:

Input: grid = ["..","#."], d = 2

Output: 4

Explanation:

Two of the routes are given in example 1. The other two routes are:

2.
#1
23
#1

Note that we can move from (1, 1) to (0, 0) because the Euclidean distance is sqrt(2) <= d.

Example 3:

Input: grid = ["#"], d = 750

Output: 0

Explanation:

We cannot choose any cell as the starting cell. Therefore, there are no routes.

Example 4:

Input: grid = [".."], d = 1

Output: 4

Explanation:

The possible routes are:

.1
1.
12
21

Constraints:

  • 1 <= n == grid.length <= 750
  • 1 <= m == grid[i].length <= 750
  • grid[i][j] is '.' or '#'.
  • 1 <= d <= 750
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given a string array grid of size n, where each string grid[i] has length m. The character grid[i][j] is one of the following symbols: '.': The cell is available. '#': The cell is blocked. You want to count the number of different routes to climb grid. Each route must start from any cell in the bottom row (row n - 1) and end in the top row (row 0). However, there are some constraints on the route. You can only move from one available cell to another available cell. The Euclidean distance of each move is at most d, where d is an integer parameter given to you. The Euclidean distance between two cells (r1, c1), (r2, c2) is sqrt((r1 - r2)2 + (c1 - c2)2). Each move either stays on the same row or moves to the row directly above (from row r to r - 1). You cannot stay on the same row for two consecutive turns. If you stay on the same row in a move (and this move is not the last move),

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Dynamic Programming

Example 1

["..","#."]
1

Example 2

["..","#."]
2

Example 3

["#"]
750
Step 02

Core Insight

What unlocks the optimal approach

  • Use dynamic programming.
  • Let <code>dp[r][c][0]</code> be the number of ways to reach <code>(r, c)</code> where the last move came from row <code>r + 1</code> (moved up), and let <code>dp[r][c][1]</code> be the number of ways where the last move stayed on row <code>r</code>.
  • Make computations faster using prefix sums over columns to aggregate contributions from cells within Euclidean distance <code>d</code>.
  • Combine <code>dp[r][c][0]</code> and <code>dp[r][c][1]</code> for all columns <code>c</code> in row <code>r</code> to produce the <code>dp</code> values used for row <code>r - 1</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3797: Count Routes to Climb a Rectangular Grid
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3797: Count Routes to Climb a Rectangular Grid
// package main
// 
// // https://space.bilibili.com/206214
// //func numberOfRoutes1(grid []string, d int) int {
// //	const mod = 1_000_000_007
// //	m := len(grid[0])
// //	f := make([]int, m+1)
// //	g := make([]int, m+1)
// //
// //	for i, row := range grid {
// //		s := make([]int, m+1)
// //		for j, ch := range row {
// //			if ch == '#' {
// //				s[j+1] = s[j]
// //			} else if i == 0 { // 第一行(起点)
// //				s[j+1] = s[j] + 1 // 原地不动,算一种方案
// //			} else {
// //				s[j+1] = (s[j] + f[min(j+d, m)] - f[max(j-d+1, 0)] + g[min(j+d, m)] - g[max(j-d+1, 0)]) % mod
// //			}
// //		}
// //		f = s
// //
// //		for j, ch := range row {
// //			if ch == '#' {
// //				g[j+1] = g[j]
// //			} else {
// //				g[j+1] = (g[j] + f[min(j+d+1, m)] - f[j+1] + f[j] - f[max(j-d, 0)]) % mod
// //			}
// //		}
// //	}
// //
// //	return (f[m] + g[m] + mod*2) % mod // +mod*2 保证结果非负
// //}
// func numberOfRoutes1(grid []string, d int) int {
// 	const mod = 1_000_000_007
// 	m := len(grid[0])
// 	sum := make([]int, m+1)
// 
// 	for i, row := range grid {
// 		// 从 i-1 行移动到 i 行的方案数
// 		f := make([]int, m)
// 		for j, ch := range row {
// 			if ch == '#' {
// 				continue
// 			}
// 			if i == 0 { // 第一行(起点)
// 				f[j] = 1 // DP 初始值
// 			} else {
// 				f[j] = sum[min(j+d, m)] - sum[max(j-d+1, 0)]
// 			}
// 		}
// 
// 		// f 的前缀和
// 		sumF := make([]int, m+1)
// 		for j, v := range f {
// 			sumF[j+1] = (sumF[j] + v) % mod
// 		}
// 
// 		// 从 i 行移动到 i 行的方案数
// 		g := make([]int, m)
// 		for j, ch := range row {
// 			if ch == '#' {
// 				continue
// 			}
// 			// 不能原地不动,减去 f[j]
// 			g[j] = sumF[min(j+d+1, m)] - sumF[max(j-d, 0)] - f[j]
// 		}
// 
// 		// f[j] + g[j] 的前缀和
// 		for j, fj := range f {
// 			sum[j+1] = (sum[j] + fj + g[j]) % mod
// 		}
// 	}
// 
// 	return (sum[m] + mod) % mod // +mod 保证结果非负
// }
// 
// func numberOfRoutes(grid []string, d int) int {
// 	const mod = 1_000_000_007
// 	m := len(grid[0])
// 	sumF := make([]int, m+1)
// 	sum := make([]int, m+1)
// 
// 	for i, row := range grid {
// 		// f 的前缀和
// 		for j, ch := range row {
// 			if ch == '#' {
// 				sumF[j+1] = sumF[j]
// 			} else if i == 0 { // 第一行(起点)
// 				sumF[j+1] = sumF[j] + 1 // DP 初始值
// 			} else {
// 				sumF[j+1] = (sumF[j] + sum[min(j+d, m)] - sum[max(j-d+1, 0)]) % mod
// 			}
// 		}
// 
// 		// f[j] + g[j] 的前缀和
// 		for j, ch := range row {
// 			if ch == '#' {
// 				sum[j+1] = sum[j]
// 			} else {
// 				// -f[j] 和 +f[j] 抵消了
// 				sum[j+1] = (sum[j] + sumF[min(j+d+1, m)] - sumF[max(j-d, 0)]) % mod
// 			}
// 		}
// 	}
// 
// 	return (sum[m] + mod) % mod // +mod 保证结果非负
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.