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 strictlyincreasing 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 modulo109 + 7.
Two paths are considered different if they do not have exactly the same sequence of visited cells.
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:
$$ \begin{bmatrix}
1 \\
2
\end{bmatrix}
$$
1
2
3
4
5
6
7
8
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.
classSolution {
privatestaticfinalint MOD = 1_000_000_007;
privateint m, n;
privateint[][] dp, grid;
privateintdfs(int i, int j) {
if (dp[i][j]!=-1) return dp[i][j];
dp[i][j]= 1; // Each cell itself is a pathint[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int[] dir : directions) {
int x = i + dir[0], y = j + dir[1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]> grid[i][j]) {
dp[i][j]= (dp[i][j]+ dfs(x, y)) % MOD;
}
}
return dp[i][j];
}
publicintcountPaths(int[][] grid) {
this.m= grid.length;
this.n= grid[0].length;
this.grid= grid;
this.dp=newint[m][n];
for (int i = 0; i < m; ++i) {
Arrays.fill(dp[i], -1);
}
int result = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
result = (result + dfs(i, j)) % MOD;
}
}
return result;
}
}
MOD =10**9+7classSolution:
defcountPaths(self, grid):
m, n = len(grid), len(grid[0])
dp = [[-1] * n for _ in range(m)]
defdfs(i, j):
if dp[i][j] !=-1:
return dp[i][j]
dp[i][j] =1# Each cell itself is a pathfor x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
if0<= x < m and0<= y < n and grid[x][y] > grid[i][j]:
dp[i][j] = (dp[i][j] + dfs(x, y)) % MOD
return dp[i][j]
result =0for i in range(m):
for j in range(n):
result = (result + dfs(i, j)) % MOD
return result