LeetCode 题解工作台
网格图中递增路径的数目
给你一个 m x n 的整数网格图 grid ,你可以从一个格子移动到 4 个方向相邻的任意一个格子。 请你返回在网格图中从 任意 格子出发,达到 任意 格子,且路径中的数字是 严格递增 的路径数目。由于答案可能会很大,请将结果对 10 9 + 7 取余 后返回。 如果两条路径中访问过的格子不是完全…
8
题型
5
代码语言
3
相关题
当前训练重点
困难 · 动态·规划
答案摘要
我们设计一个函数 $dfs(i, j)$,表示从网格图中的第 行第 列的格子出发,能够到达任意格子的严格递增路径数目。那么答案就是 $\sum_{i=0}^{m-1} \sum_{j=0}^{n-1} dfs(i, j)$。搜索过程中,我们可以用一个二维数组 记录已经计算过的结果,避免重复计算。 函数 $dfs(i, j)$ 的计算过程如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 动态·规划 题型思路
题目描述
给你一个 m x n 的整数网格图 grid ,你可以从一个格子移动到 4 个方向相邻的任意一个格子。
请你返回在网格图中从 任意 格子出发,达到 任意 格子,且路径中的数字是 严格递增 的路径数目。由于答案可能会很大,请将结果对 109 + 7 取余 后返回。
如果两条路径中访问过的格子不是完全相同的,那么它们视为两条不同的路径。
示例 1:

输入:grid = [[1,1],[3,4]] 输出:8 解释:严格递增路径包括: - 长度为 1 的路径:[1],[1],[3],[4] 。 - 长度为 2 的路径:[1 -> 3],[1 -> 4],[3 -> 4] 。 - 长度为 3 的路径:[1 -> 3 -> 4] 。 路径数目为 4 + 3 + 1 = 8 。
示例 2:
输入:grid = [[1],[2]] 输出:3 解释:严格递增路径包括: - 长度为 1 的路径:[1],[2] 。 - 长度为 2 的路径:[1 -> 2] 。 路径数目为 2 + 1 = 3 。
提示:
m == grid.lengthn == grid[i].length1 <= m, n <= 10001 <= m * n <= 1051 <= grid[i][j] <= 105
解题思路
方法一:记忆化搜索
我们设计一个函数 ,表示从网格图中的第 行第 列的格子出发,能够到达任意格子的严格递增路径数目。那么答案就是 。搜索过程中,我们可以用一个二维数组 记录已经计算过的结果,避免重复计算。
函数 的计算过程如下:
- 如果 不为 ,说明已经计算过,直接返回 ;
- 否则,我们初始化 ,然后枚举 的四个方向,如果某个方向的格子 满足 , 且 ,我们就可以从格子 出发,到达格子 ,且路径上的数字是严格递增的,因此有 。
最后,我们返回 。
答案为 。
时间复杂度 ,空间复杂度 。其中 和 分别是网格图的行数和列数。
相似题目:
class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
@cache
def dfs(i: int, j: int) -> int:
ans = 1
for a, b in pairwise((-1, 0, 1, 0, -1)):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid[i][j] < grid[x][y]:
ans = (ans + dfs(x, y)) % mod
return ans
mod = 10**9 + 7
m, n = len(grid), len(grid[0])
return sum(dfs(i, j) for i in range(m) for j in range(n)) % mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They want you to notice the grid forms a DAG because values must strictly increase on every move.
- question_mark
A strong answer explains why each cell starts with one path before extending counts to larger neighbors.
- question_mark
If you mention both memoized DFS and indegree topological DP, then justify why the graph ordering is clean here, that is usually a positive signal.
常见陷阱
外企场景- error
Forgetting that every single cell counts as its own increasing path, which undercounts examples like [[1],[2]].
- error
Adding edges between equal values or using non-strict comparisons, which creates invalid transitions for this exact problem.
- error
Applying modulo only at the very end, which risks overflow and makes intermediate DP updates incorrect in large grids.
进阶变体
外企场景- arrow_right_alt
Solve the same grid by memoized DFS where dp[i][j] stores the number of increasing paths starting at cell (i, j).
- arrow_right_alt
Count decreasing paths instead by reversing the comparison direction or flipping edge construction.
- arrow_right_alt
Return the longest increasing path length instead of the total count, which changes the DP transition from summation to maximization.