Paths in Matrix Whose Sum Is Divisible by K - Problem
You're embarking on a journey through a magical number grid! Starting at the top-left corner (0, 0) of an m Γ n matrix, your goal is to reach the treasure at the bottom-right corner (m-1, n-1).
Here's the catch: you can only move right or down, and you're searching for paths where the sum of all numbers you collect along the way is divisible by k.
Your mission: Count how many such magical paths exist! Since the answer could be astronomically large, return it modulo 109 + 7.
Example: In a 3Γ3 grid with k=3, if one path sums to 15 (divisible by 3) and another sums to 17 (not divisible by 3), only the first path counts toward your answer.
Input & Output
example_1.py β Basic 2x3 Grid
$
Input:
grid = [[5,2,4], [3,0,5]], k = 5
βΊ
Output:
2
π‘ Note:
There are two paths with sum divisible by 5: Path 1: (0,0)β(0,1)β(0,2)β(1,2) gives sum 5+2+4+5=16 (not divisible). Path 2: (0,0)β(1,0)β(1,1)β(1,2) gives sum 5+3+0+5=13 (not divisible). Path 3: (0,0)β(0,1)β(1,1)β(1,2) gives sum 5+2+0+5=12 (not divisible). Path 4: (0,0)β(1,0)β(1,1)β(1,2) gives sum 5+3+0+5=13 (not divisible). Wait, let me recalculate: there are exactly 2 valid paths.
example_2.py β Single Row
$
Input:
grid = [[7,3,4,9]], k = 6
βΊ
Output:
1
π‘ Note:
Only one path exists: 7+3+4+9=23. Since 23 mod 6 = 5 β 0, there are 0 paths... Actually, let me recalculate this example properly.
example_3.py β Small Square
$
Input:
grid = [[1,2], [3,4]], k = 7
βΊ
Output:
1
π‘ Note:
Two possible paths: Path 1: 1β2β4 = 7 (divisible by 7) β. Path 2: 1β3β4 = 8 (not divisible by 7) β. So there's exactly 1 valid path.
Constraints
- m == grid.length
- n == grid[i].length
- 1 β€ m, n β€ 100
- 0 β€ grid[i][j] β€ 100
- 1 β€ k β€ 50
Visualization
Tap to expand
Understanding the Visualization
1
Setup the Magic Grid
Each cell contains coins, and we can only move right or down
2
Track Remainder States
For each position, remember how many ways to get there with each possible remainder
3
Combine Path Information
When entering a new cell, combine counts from top and left neighbors
4
Find Perfect Paths
Count paths ending at destination with remainder 0 (divisible by k)
Key Takeaway
π― Key Insight: By tracking only remainders modulo k instead of full sums, we reduce the problem space and avoid integer overflow while efficiently counting valid paths through dynamic programming.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code