|
| 1 | +# 2435. Paths in Matrix Whose Sum Is Divisible by K |
| 2 | + |
| 3 | +# 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. |
| 4 | + |
| 5 | +# 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. |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | +# Example 1: |
| 10 | + |
| 11 | + |
| 12 | +# Input: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3 |
| 13 | +# Output: 2 |
| 14 | +# Explanation: There are two paths where the sum of the elements on the path is divisible by k. |
| 15 | +# The first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3. |
| 16 | +# The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3. |
| 17 | +# Example 2: |
| 18 | + |
| 19 | + |
| 20 | +# Input: grid = [[0,0]], k = 5 |
| 21 | +# Output: 1 |
| 22 | +# Explanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5. |
| 23 | +# Example 3: |
| 24 | + |
| 25 | + |
| 26 | +# Input: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1 |
| 27 | +# Output: 10 |
| 28 | +# Explanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k. |
| 29 | + |
| 30 | + |
| 31 | +# Constraints: |
| 32 | + |
| 33 | +# m == grid.length |
| 34 | +# n == grid[i].length |
| 35 | +# 1 <= m, n <= 5 * 104 |
| 36 | +# 1 <= m * n <= 5 * 104 |
| 37 | +# 0 <= grid[i][j] <= 100 |
| 38 | +# 1 <= k <= 50 |
| 39 | + |
| 40 | + |
| 41 | +class Solution: |
| 42 | + def numberOfPaths(self, grid, k): |
| 43 | + MOD = 10**9 + 7 |
| 44 | + m, n = len(grid), len(grid[0]) |
| 45 | + |
| 46 | + # dp[i][j][mod] = ways to reach (i,j) with sum % k = mod |
| 47 | + dp = [[[0] * k for _ in range(n)] for _ in range(m)] |
| 48 | + dp[0][0][grid[0][0] % k] = 1 |
| 49 | + |
| 50 | + for i in range(m): |
| 51 | + for j in range(n): |
| 52 | + for mod in range(k): |
| 53 | + if dp[i][j][mod] > 0: |
| 54 | + if i + 1 < m: |
| 55 | + new_mod = (mod + grid[i+1][j]) % k |
| 56 | + dp[i+1][j][new_mod] = (dp[i+1][j][new_mod] + dp[i][j][mod]) % MOD |
| 57 | + if j + 1 < n: |
| 58 | + new_mod = (mod + grid[i][j+1]) % k |
| 59 | + dp[i][j+1][new_mod] = (dp[i][j+1][new_mod] + dp[i][j][mod]) % MOD |
| 60 | + |
| 61 | + return dp[m-1][n-1][0] |
0 commit comments