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.
classSolution { longlong mod = 1e9 + 7; vector<vector<longlong>> dp; longlong n, m; int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1}; longlongdfs(int y, int x, vector<vector<int>>& g){ if(dp[y][x] != -1) return dp[y][x]; longlong& 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 and0 <= nx and nx < m and g[y][x] < g[ny][nx]) { res = (res + dfs(ny,nx,g)) % mod; } } return res; } public: intcountPaths(vector<vector<int>>& grid){ n = grid.size(), m = grid[0].size(); longlong res = 0; dp = vector<vector<longlong>> (n, vector<longlong>(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; } };