|
| 1 | +from typing import List |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + """Base class for all LeetCode Problems.""" |
| 6 | + |
| 7 | + def numberOfPathsTD(self, grid: List[List[int]], k: int) -> int: |
| 8 | + """ |
| 9 | + You are given a 0-indexed m x n integer matrix grid and an integer k. |
| 10 | + You are currently at position (0, 0) and you want to reach position |
| 11 | + (m - 1, n - 1) moving only down or right. |
| 12 | +
|
| 13 | + Return the number of paths where the sum of the elements on the path is |
| 14 | + divisible by k. Since the answer may be very large, return it modulo 109 + 7. |
| 15 | + """ |
| 16 | + # Top-Down Dynamic Programming (Memoization) |
| 17 | + ROWS = len(grid) |
| 18 | + COLS = len(grid[0]) |
| 19 | + MOD = 10**9 + 7 |
| 20 | + dp = [[[-1] * k for _ in range(COLS)] for _ in range(ROWS)] |
| 21 | + |
| 22 | + def dfs(row: int, col: int, remain: int): |
| 23 | + if row == ROWS - 1 and col == COLS - 1: |
| 24 | + remain = (grid[row][col] + remain) % k |
| 25 | + return 0 if remain else 1 |
| 26 | + if row == ROWS or col == COLS: |
| 27 | + return 0 |
| 28 | + if dp[row][col][remain] > -1: |
| 29 | + return dp[row][col][remain] |
| 30 | + dp[row][col][remain] = ( |
| 31 | + dfs(row + 1, col, (grid[row][col] + remain) % k) % MOD |
| 32 | + + dfs(row, col + 1, (grid[row][col] + remain) % k) % MOD |
| 33 | + ) % MOD |
| 34 | + return dp[row][col][remain] |
| 35 | + |
| 36 | + return dfs(0, 0, 0) |
| 37 | + |
| 38 | + def numberOfPathsBU(self, grid: List[List[int]], k: int) -> int: |
| 39 | + """ |
| 40 | + You are given a 0-indexed m x n integer matrix grid and an integer k. |
| 41 | + You are currently at position (0, 0) and you want to reach position |
| 42 | + (m - 1, n - 1) moving only down or right. |
| 43 | +
|
| 44 | + Return the number of paths where the sum of the elements on the path is |
| 45 | + divisible by k. Since the answer may be very large, return it modulo 109 + 7. |
| 46 | + """ |
| 47 | + # Bottom-Up Dynamic Programming (Tabulation) |
| 48 | + ROWS = len(grid) |
| 49 | + COLS = len(grid[0]) |
| 50 | + MOD = 10**9 + 7 |
| 51 | + dp = [[[0] * k for _ in range(COLS + 1)] for _ in range(ROWS + 1)] |
| 52 | + target_remain = (k - (grid[ROWS - 1][COLS - 1] % k)) % k |
| 53 | + dp[ROWS - 1][COLS - 1][target_remain] = 1 |
| 54 | + |
| 55 | + for row in reversed(range(ROWS)): |
| 56 | + for col in reversed(range(COLS)): |
| 57 | + if row == ROWS - 1 and col == COLS - 1: |
| 58 | + continue |
| 59 | + for remain in range(k): |
| 60 | + new_remain = (grid[row][col] + remain) % k |
| 61 | + dp[row][col][remain] = ( |
| 62 | + dp[row + 1][col][new_remain] % MOD |
| 63 | + + dp[row][col + 1][new_remain] % MOD |
| 64 | + ) % MOD |
| 65 | + |
| 66 | + return dp[0][0][0] |
0 commit comments