classSolution: defnumberOfPaths(self, grid: List[List[int]], k: int) -> int: MOD = 10 ** 9 + 7 m, n = len(grid), len(grid[0]) f = [[[0] * k for _ inrange(n + 1)] for _ inrange(m + 1)] f[0][1][0] = 1 for i, row inenumerate(grid): for j, x inenumerate(row): for v inrange(k): f[i + 1][j + 1][(v + x) % k] = (f[i + 1][j][v] + f[i][j + 1][v]) % MOD return f[m][n][0]
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { publicintnumberOfPaths(int[][] grid, int k) { finalvarmod= (int) 1e9 + 7; intm= grid.length, n = grid[0].length; varf=newint[m + 1][n + 1][k]; f[0][1][0] = 1; for (vari=0; i < m; ++i) for (varj=0; j < n; ++j) for (varv=0; v < k; ++v) f[i + 1][j + 1][(v + grid[i][j]) % k] = (f[i + 1][j][v] + f[i][j + 1][v]) % mod; return f[m][n][0]; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: intnumberOfPaths(vector<vector<int>> &grid, int k){ constint mod = 1e9 + 7; int m = grid.size(), n = grid[0].size(), f[m + 1][n + 1][k]; memset(f, 0, sizeof(f)); f[0][1][0] = 1; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) for (int v = 0; v < k; ++v) f[i + 1][j + 1][(v + grid[i][j]) % k] = (f[i + 1][j][v] + f[i][j + 1][v]) % mod; return f[m][n][0]; } };
funcnumberOfPaths(grid [][]int, k int)int { const mod int = 1e9 + 7 m, n := len(grid), len(grid[0]) f := make([][][]int, m+1) for i := range f { f[i] = make([][]int, n+1) for j := range f[i] { f[i][j] = make([]int, k) } } f[0][1][0] = 1 for i, row := range grid { for j, x := range row { for v := 0; v < k; v++ { f[i+1][j+1][(v+x)%k] = (f[i+1][j][v] + f[i][j+1][v]) % mod } } } return f[m][n][0] }