Problem Description
Given an m x n integer matrix grid and an integer k, you need to count the number of paths from the top-left cell (0, 0) to the bottom-right cell (m - 1, n - 1) by moving only down or right such that the sum of the elements on the path is divisible by k. The final count should be returned modulo 10^9+7.
Key Insights
- Use dynamic programming to traverse the grid while maintaining the sum modulo k.
- At every cell, consider paths coming from the top and left; accumulate ways based on current cell value.
- The state representation is dp[i][j][r] where r represents the remainder (sum % k) of the path reaching (i, j).
- Since k is relatively small (up to 50) and total grid cells are at most 5 * 10^4, a 3D DP state is feasible.
- Always take modulo arithmetic (10^9+7) to avoid overflow.
Space and Time Complexity
Time Complexity: O(m * n * k)
Space Complexity: O(m * n * k)
Solution
We solve the problem using a dynamic programming (DP) approach where each cell maintains an array (or vector) of length k. Each index of this array represents the number of ways to reach that cell with a particular sum remainder modulo k.
- Initialize dp[0][0][grid[0][0] % k] = 1.
- For each cell (i, j), update its DP state by considering contributions from the top (i-1, j) and left (i, j-1). For every remainder from a previous cell, update the current remainder r_new = (previous remainder + grid[i][j]) % k.
- Continue processing the grid until the bottom-right cell is reached.
- The answer is the value at dp[m-1][n-1][0] since a remainder 0 indicates that the sum is divisible by k.
- Take modulo 10^9+7 at each step to manage large numbers.