08. Number of Paths in a Matrix with K Coins
β GFG solution to the Number of Paths in a Matrix with K Coins problem: count paths from top-left to bottom-right collecting exactly k coins using optimized dynamic programming. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a matrix mat[][] of size n x m, where each cell contains some coins. Your task is to count the number of ways to collect exactly k coins while moving from the top-left cell to the bottom-right cell.
From a cell (i, j), you can only move to:
Cell
(i+1, j)(down)Cell
(i, j+1)(right)
π Examples
Example 1
Input: k = 12, mat[][] = [[1, 2, 3],
[4, 6, 5],
[3, 2, 1]]
Output: 2
Explanation: There are 2 possible paths with exactly 12 coins:
- Path 1: 1 + 2 + 6 + 2 + 1 = 12
- Path 2: 1 + 2 + 3 + 5 + 1 = 12Example 2
Input: k = 16, mat[][] = [[1, 2, 3],
[4, 6, 5],
[9, 8, 7]]
Output: 0
Explanation: There are no possible paths that sum to exactly 16 coins.π Constraints
$1 \le k \le 100$
$1 \le n, m \le 100$
$0 \le \text{mat}[i][j] \le 200$
β
My Approach
The optimal approach uses Dynamic Programming with Space Optimization to efficiently count paths while tracking coin sums:
2D Row-Optimized DP
State Definition:
dp[j][s]= number of ways to reach columnjin current row with sumsWe only need to track the previous row, not the entire matrix history
Initialization:
Start at
(0, 0)withmat[0][0]coinsInitialize first row by moving right, accumulating coins
Row-by-Row Processing:
For each new row, create a fresh DP table
For each cell
(i, j):Can reach from left:
ndp[j-1][s - mat[i][j]]Can reach from top:
dp[j][s - mat[i][j]]
Sum both contributions for total paths to
(i, j)with sums
Space Optimization:
Only maintain DP arrays for current and previous row
Reduces space from O(n Γ m Γ k) to O(m Γ k)
Result Extraction:
Return
dp[m-1][k]= paths reaching bottom-right with exactly k coins
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n Γ m Γ k), where n and m are matrix dimensions and k is the target sum. For each of the n Γ m cells, we iterate through all possible sums up to k to compute the number of paths.
Expected Auxiliary Space Complexity: O(m Γ k), as we maintain only two rows of the DP table at any time (current and previous row), each storing states for m columns and k+1 possible sums. This is a significant optimization over the naive O(n Γ m Γ k) space approach.
π§βπ» Code (C++)
class Solution {
public:
int numberOfPath(vector<vector<int>>& mat, int k) {
int n = mat.size(), m = mat[0].size();
vector<vector<int>> dp(m, vector<int>(k + 1, 0));
if (mat[0][0] <= k) dp[0][mat[0][0]] = 1;
for (int j = 1; j < m; j++)
for (int s = mat[0][j]; s <= k; s++)
dp[j][s] = dp[j - 1][s - mat[0][j]];
for (int i = 1; i < n; i++) {
vector<vector<int>> ndp(m, vector<int>(k + 1, 0));
if (mat[i][0] <= k)
for (int s = mat[i][0]; s <= k; s++)
ndp[0][s] = dp[0][s - mat[i][0]];
for (int j = 1; j < m; j++)
for (int s = mat[i][j]; s <= k; s++)
ndp[j][s] = ndp[j - 1][s - mat[i][j]] + dp[j][s - mat[i][j]];
dp = ndp;
}
return dp[m - 1][k];
}
};β Code (Java)
class Solution {
public int numberOfPath(int[][] mat, int k) {
int n = mat.length, m = mat[0].length;
int[][] dp = new int[m][k + 1];
if (mat[0][0] <= k) dp[0][mat[0][0]] = 1;
for (int j = 1; j < m; j++)
for (int s = mat[0][j]; s <= k; s++)
dp[j][s] = dp[j - 1][s - mat[0][j]];
for (int i = 1; i < n; i++) {
int[][] ndp = new int[m][k + 1];
if (mat[i][0] <= k)
for (int s = mat[i][0]; s <= k; s++)
ndp[0][s] = dp[0][s - mat[i][0]];
for (int j = 1; j < m; j++)
for (int s = mat[i][j]; s <= k; s++)
ndp[j][s] = ndp[j - 1][s - mat[i][j]] + dp[j][s - mat[i][j]];
dp = ndp;
}
return dp[m - 1][k];
}
}π Code (Python)
class Solution:
def numberOfPath(self, mat, k):
n, m = len(mat), len(mat[0])
dp = [[0] * (k + 1) for _ in range(m)]
if mat[0][0] <= k:
dp[0][mat[0][0]] = 1
for j in range(1, m):
for s in range(mat[0][j], k + 1):
dp[j][s] = dp[j - 1][s - mat[0][j]]
for i in range(1, n):
ndp = [[0] * (k + 1) for _ in range(m)]
if mat[i][0] <= k:
for s in range(mat[i][0], k + 1):
ndp[0][s] = dp[0][s - mat[i][0]]
for j in range(1, m):
for s in range(mat[i][j], k + 1):
ndp[j][s] = ndp[j - 1][s - mat[i][j]] + dp[j][s - mat[i][j]]
dp = ndp
return dp[m - 1][k]π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated