[LeetCode] Paths in Matrix Whose Sum Is Divisible by K

2435. Paths in Matrix Whose Sum Is Divisible by K

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int numberOfPaths(vector<vector<int>>& A, int k) {
int n = A.size(), m = A[0].size();
long long mod = 1e9 + 7;
vector<vector<vector<long long>>> dp(n,vector<vector<long long>>(m, vector<long long>(k)));
dp[0][0][A[0][0]%k] = 1;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int l = 0; l < k; l++) {
if(i) dp[i][j][(l + A[i][j])%k] = (dp[i][j][(l + A[i][j])%k] + dp[i-1][j][l]) % mod;
if(j) dp[i][j][(l + A[i][j])%k] = (dp[i][j][(l + A[i][j])%k] + dp[i][j-1][l]) % mod;
}
}
}
return dp[n-1][m-1][0];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/09/PS/LeetCode/paths-in-matrix-whose-sum-is-divisible-by-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.