[LeetCode] Number of Increasing Paths in a Grid

2328. Number of Increasing Paths in a Grid

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 109 + 7.

Two paths are considered different if they do not have exactly the same sequence of visited cells.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
long long mod = 1e9 + 7;
vector<vector<long long>> dp;
long long n, m;
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
long long dfs(int y, int x, vector<vector<int>>& g) {
if(dp[y][x] != -1) return dp[y][x];
long long& res = dp[y][x] = 1;
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and g[y][x] < g[ny][nx]) {
res = (res + dfs(ny,nx,g)) % mod;
}
}
return res;
}
public:
int countPaths(vector<vector<int>>& grid) {
n = grid.size(), m = grid[0].size();
long long res = 0;
dp = vector<vector<long long>> (n, vector<long long>(m, -1));

for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
res = (res + dfs(i,j,grid)) % mod;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/03/PS/LeetCode/number-of-increasing-paths-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.