2435. Paths in Matrix Whose Sum Is Divisible by K #2466
-
|
Topics: You are given a 0-indexed Return the number of paths where the sum of the elements on the path is divisible by Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find the number of paths from top-left to bottom-right in a matrix where the sum of elements along the path is divisible by k, moving only right or down. Approach:Problem Analysis
Dynamic Programming ApproachI'll use a 2D DP array where Since we process row by row, I can optimize space by only storing the current and previous row information. Let's implement this solution in PHP: 2435. Paths in Matrix Whose Sum Is Divisible by K <?php
/**
* @param Integer[][] $grid
* @param Integer $k
* @return Integer
*/
function numberOfPaths($grid, $k) {
$MOD = 1000000007;
$m = count($grid);
$n = count($grid[0]);
// 3D DP: dp[i][j][r] = paths to (i,j) with remainder r
$dp = array_fill(0, $m, array_fill(0, $n, array_fill(0, $k, 0)));
// Initialize starting cell
$firstRem = $grid[0][0] % $k;
$dp[0][0][$firstRem] = 1;
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
$currentVal = $grid[$i][$j] % $k;
// Skip reprocessing the start cell
if ($i == 0 && $j == 0) continue;
// Check paths from top
if ($i > 0) {
for ($r = 0; $r < $k; $r++) {
if ($dp[$i-1][$j][$r] > 0) {
$newRem = ($r + $currentVal) % $k;
$dp[$i][$j][$newRem] = ($dp[$i][$j][$newRem] + $dp[$i-1][$j][$r]) % $MOD;
}
}
}
// Check paths from left
if ($j > 0) {
for ($r = 0; $r < $k; $r++) {
if ($dp[$i][$j-1][$r] > 0) {
$newRem = ($r + $currentVal) % $k;
$dp[$i][$j][$newRem] = ($dp[$i][$j][$newRem] + $dp[$i][$j-1][$r]) % $MOD;
}
}
}
}
}
return $dp[$m-1][$n-1][0];
}
// Test cases
echo numberOfPaths([[5,2,4],[3,0,5],[0,7,2]], 3) . "\n"; // Output: 2
echo numberOfPaths([[0,0]], 5) . "\n"; // Output: 1
echo numberOfPaths([[7,3,4,9],[2,3,6,2],[2,3,7,0]], 1) . "\n"; // Output: 10
?>Explanation:
Complexity Analysis
|
Beta Was this translation helpful? Give feedback.



We need to find the number of paths from top-left to bottom-right in a matrix where the sum of elements along the path is divisible by k, moving only right or down.
Approach:
Problem Analysis
Dynamic Programming Approach
I'll use a 2D DP array where
dp[j][r]represents the number of paths to current column j with remainder r.Since we process row by row, I can optimize space by only storing the current and previous row information.
Let's implement this solution in PHP: 2435. Paths in Matrix Whose Sum Is Divisible by K