Number of Increasing Paths in a Grid Problem
Description
LeetCode Problem 2328.
You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions.
Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 10^9 + 7.
Two paths are considered different if they do not have exactly the same sequence of visited cells.
Example 1:

Input: grid = [[1,1],[3,4]]
Output: 8
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [1], [3], [4].
- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].
- Paths with length 3: [1 -> 3 -> 4].
The total number of paths is 4 + 3 + 1 = 8.
Example 2:
Input: grid = [[1],[2]]
Output: 3
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [2].
- Paths with length 2: [1 -> 2].
The total number of paths is 2 + 1 = 3.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10001 <= m * n <= 10^51 <= grid[i][j] <= 10^5
Solution
Approach: DFS + Memoization
Let f[i][j] be the number of strictly increasing paths that start at cell (i, j). The cell alone is one path, and for every neighbor (x, y) with a larger value, each path starting at (x, y) extends to a path starting at (i, j). So f[i][j] = 1 + sum of f[x][y] over those neighbors.
Because values strictly increase along a path, there are no cycles, and memoizing f makes each cell computed once. The answer is the sum of all f[i][j] modulo 10^9 + 7.
Complexity: Time O(m * n), space O(m * n).
from functools import lru_cache
class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
@lru_cache(None)
def dfs(i: int, j: int) -> int:
ans = 1
for a, b in zip((-1, 0, 1, 0), (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