Skip to content

Commit 1bdb26b

Browse files
authored
Create 2435. Paths in Matrix Whose Sum Is Divisible by K (#943)
2 parents 5c743f2 + 5e49506 commit 1bdb26b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// no branch
2+
class Solution {
3+
public:
4+
static int numberOfPaths(vector<vector<int>>& grid, int k) {
5+
const int m=grid.size(), n=grid[0].size();
6+
const int mod=1e9+7;
7+
int dp[2][n][k];
8+
memset(dp, 0, sizeof(dp));
9+
dp[0][0][(k-grid[0][0]%k)%k]=1;
10+
for(int j=1; j<n; j++){
11+
const int x=grid[0][j];
12+
for(int r=0; r<k; r++){
13+
dp[0][j][r]+=dp[0][j-1][(x+r)%k];
14+
dp[0][j][r]%=mod;
15+
}
16+
}
17+
for(int i=1; i<m; i++){
18+
const int x0=grid[i][0];
19+
for(int r=0; r<k; r++){
20+
dp[i&1][0][r]=dp[(i-1)&1][0][(r+x0)%k];
21+
}
22+
for(int j=1; j<n; j++){
23+
const int x=grid[i][j];
24+
for(int r=0; r<k; r++){
25+
const int R0=(r+x)%k;
26+
dp[i&1][j][r]=dp[(i-1)&1][j][R0];
27+
dp[i&1][j][r]+=dp[i&1][j-1][R0];
28+
dp[i&1][j][r]%=mod;
29+
}
30+
}
31+
}
32+
return dp[(m-1)&1][n-1][0];
33+
}
34+
};

0 commit comments

Comments
 (0)