LeetCode 2435. Paths in Matrix Whose Sum Is Divisible by K Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
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.length
  • n == grid[i].length
  • 1 <= m, n <= 5 * 104
  • 1 <= m * n <= 5 * 104
  • 0 <= grid[i][j] <= 100
  • 1 <= k <= 50

Solutions

Solution 1: Dynamic Programming

We denote the k in the problem as K, and let m and n be the number of rows and columns of the matrix grid, respectively.

Define f[i][j][k] as the number of paths starting from (0, 0), reaching position (i, j), where the sum of elements along the path modulo K equals k. Initially, f[0][0][grid[0][0] \bmod K] = 1. The final answer is f[m - 1][n - 1][0].

We can derive the state transition equation:

f[i][j][k] = f[i - 1][j][(k - grid[i][j])\bmod K] + f[i][j - 1][(k - grid[i][j])\bmod K]

To avoid issues with negative modulo operations, we can replace (k - grid[i][j])\bmod K in the above equation with ((k - grid[i][j] \bmod K) + K) \bmod K.

The answer is f[m - 1][n - 1][0].

The time complexity is O(m × n × K) and the space complexity is O(m × n × K), where m and n are the number of rows and columns of the matrix grid, respectively, and K is the integer k from the problem.

PythonJavaC++GoTypeScriptRustC#
class Solution: def numberOfPaths(self, grid: List[List[int]], K: int) -> int: mod = 10**9 + 7 m, n = len(grid), len(grid[0]) f = [[[0] * K for _ in range(n)] for _ in range(m)] f[0][0][grid[0][0] % K] = 1 for i in range(m): for j in range(n): for k in range(K): k0 = ((k - grid[i][j] % K) + K) % K if i: f[i][j][k] += f[i - 1][j][k0] if j: f[i][j][k] += f[i][j - 1][k0] f[i][j][k] %= mod return f[m - 1][n - 1][0](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !