classSolution: defcountPaths(self, grid: List[List[int]]) -> int: MOD = 10 ** 9 + 7 m, n = len(grid), len(grid[0]) @cache defdfs(i: int, j: int) -> int: res = 1 for 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]: res += dfs(x, y) return res % MOD returnsum(dfs(i, j) for i inrange(m) for j inrange(n)) % MOD
publicintcountPaths(int[][] grid) { m = grid.length; n = grid[0].length; this.grid = grid; f = newint[m][n]; for (inti=0; i < m; i++) Arrays.fill(f[i], -1); varans=0; for (vari=0; i < m; ++i) for (varj=0; j < n; ++j) ans = (ans + dfs(i, j)) % MOD; return ans; }
intdfs(int i, int j) { if (f[i][j] != -1) return f[i][j]; varres=1; for (var d : dirs) { intx= i + d[0], y = j + d[1]; if (0 <= x && x < m && 0 <= y && y < n && grid[x][y] > grid[i][j]) res = (res + (dfs(x, y))) % MOD; } return f[i][j] = res; } }
classSolution { constint MOD = 1e9 + 7; constint dirs[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; public: intcountPaths(vector<vector<int>> &grid){ int m = grid.size(), n = grid[0].size(); int f[m][n]; memset(f, -1, sizeof(f)); function<int(int, int)> dfs = [&](int i, int j) -> int { if (f[i][j] != -1) return f[i][j]; int res = 1; for (auto &d : dirs) { int x = i + d[0], y = j + d[1]; if (0 <= x && x < m && 0 <= y && y < n && grid[x][y] > grid[i][j]) res = (res + (dfs(x, y))) % MOD; } return f[i][j] = res; }; int ans = 0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) ans = (ans + dfs(i, j)) % MOD; return ans; } };
var dirs = []struct{ x, y int }{ {-1, 0}, {1, 0}, {0, -1}, {0, 1} }
funccountPaths(grid [][]int) (ans int) { const mod int = 1e9 + 7 m, n := len(grid), len(grid[0]) f := make([][]int, m) for i := range f { f[i] = make([]int, n) for j := range f[i] { f[i][j] = -1 } } var dfs func(int, int)int dfs = func(i, j int)int { if f[i][j] != -1 { return f[i][j] } res := 1 for _, d := range dirs { if x, y := i+d.x, j+d.y; 0 <= x && x < m && 0 <= y && y < n && grid[x][y] > grid[i][j] { res = (res + dfs(x, y)) % mod } } f[i][j] = res return res } for i, row := range grid { for j := range row { ans = (ans + dfs(i, j)) % mod } } return }