LeetCode 2435: Paths in Matrix Whose Sum Is Divisible by K
Problem Description
Explanation:
To solve this problem, we can utilize dynamic programming. We will maintain a 2D array dp
where dp[i][j]
represents the number of paths from (0,0)
to (i,j)
whose sum of elements is divisible by k
.
We can fill up the dp
array by iterating row by row and column by column. For each cell (i,j)
in the grid, the number of paths to reach that cell is the sum of paths coming from the cell above (i-1, j)
and the cell on the left (i, j-1)
.
To calculate the sum of elements along the path, we need to consider the current element in the grid as well. If the sum of elements along the path to (i,j)
is divisible by k
, we increment the count in dp[i][j]
.
Finally, the result will be stored in dp[m-1][n-1]
.
Time Complexity: The time complexity of this approach is O(m*n) where m and n are the dimensions of the input matrix.
Space Complexity:
The space complexity is also O(m*n) for the dp
array.
Solutions
class Solution {
public int countPaths(int[][] grid, int k) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
dp[0][0] = (grid[0][0] % k == 0) ? 1 : 0;
for (int i = 1; i < m; i++) {
dp[i][0] = (dp[i - 1][0] + grid[i][0]) % k == 0 ? 1 : 0;
}
for (int j = 1; j < n; j++) {
dp[0][j] = (dp[0][j - 1] + grid[0][j]) % k == 0 ? 1 : 0;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % k == 0 ? 1 : 0;
}
}
return dp[m - 1][n - 1];
}
}
Loading editor...