2435. Paths in Matrix Whose Sum Is Divisible by K
Description
You are given a 0-indexed m x n integer matrix grid and an integer k. You are currently at position (0, 0) and you want to reach position (m - 1, n - 1) moving only down or right.
Return the number of paths where the sum of the elements on the path is divisible by k. Since the answer may be very large, return it modulo 109 + 7.
Example 1:

Input: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3 Output: 2 Explanation: There are two paths where the sum of the elements on the path is divisible by k. The first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3. The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3.
Example 2:

Input: grid = [[0,0]], k = 5 Output: 1 Explanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5.
Example 3:

Input: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1 Output: 10 Explanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 5 * 1041 <= m * n <= 5 * 1040 <= grid[i][j] <= 1001 <= k <= 50
Solutions
Solution: Dynamic Programming
- Time complexity: O(mnk)
- Space complexity: O(mnk)
JavaScript
js
/**
* @param {number[][]} grid
* @param {number} k
* @return {number}
*/
const numberOfPaths = function (grid, k) {
const MODULO = 10 ** 9 + 7;
const m = grid.length;
const n = grid[0].length;
const dp = Array.from({ length: m }, () => {
return new Array(n)
.fill('')
.map(() => new Array(k + 1).fill(-1));
});
const divisiblePaths = (row, col, current) => {
if (row >= m || col >= n) return 0;
if (dp[row][col][current] !== -1) return dp[row][col][current];
const value = grid[row][col];
const nextCurrent = (current + value) % k;
if (row === m - 1 && col === n - 1) return nextCurrent ? 0 : 1;
const downPaths = divisiblePaths(row + 1, col, nextCurrent);
const rightPaths = divisiblePaths(row, col + 1, nextCurrent);
const paths = (downPaths + rightPaths) % MODULO;
dp[row][col][current] = paths;
return paths;
};
return divisiblePaths(0, 0, 0);
};