GeeksforGeeks: Number of paths with exactly k coins

Given a matrix where every cell has some number of coins. Count number of ways to reach bottom right from top left with exactly k coins. We can move to (i+1, j) and (i, j+1) from a cell (i, j).
Example:
Input:  k = 12
        mat[][] = { {1, 2, 3},
                    {4, 6, 5},
                    {3, 2, 1}
                  };
Output:  2
There are two paths with 12 coins
1 -> 2 -> 6 -> 2 -> 1
1 -> 2 -> 3 -> 5 -> 1

Solution:

pathCount(i, j, k):   Number of paths to reach mat[0][0] from mat[m][n] 
                      with exactly k coins

If (i == m and j == n)
   return 1 if mat[m][n] == k else return 0
Else:
    pathCount(i, j, k) = pathCount(i+1, n, k - mat[i][j]) + 
                         pathCount(m, j+1, k - mat[][j]) 
 public int pathCount(int[][] mat, int k) {
  return pathCountHelper(mat,0,0,k); 
 }
 
 public int pathCountHelper(int[][] mat, int i, int j, int sum) {
  //sum= maxtrix[i][j] 减前
  if(i == mat.length - 1 && j == mat[0].length - 1) {
   if(sum == mat[i][j]) return 1;
   else return 0;
  }else {
   if(i >= mat.length || j >= mat[0].length)
    return 0;
   return this.pathCountHelper(mat, i+1, j, sum-mat[i][j])
     + this.pathCountHelper(mat, i, j+1, sum-mat[i][j]);
  }
 }
 public int pathCountDP(int[][] mat, int k) {
  int m = mat.length;
  int n = mat[0].length;
  int[][][] dp = new int[m][n][k];
  for(int i = 0; i < m ; i++) {
   for(int j = 0; j < n; j++) {
    for(int l = 0 ; l < k; l++) {
     dp[i][j][l] = -1;
    }
   }
  }
  return pathCountDPHelper(mat,0,0,k,dp); 
 }
 
 public int pathCountDPHelper(int[][] mat, int i, int j, int sum, int[][][] dp) {
  //sum减前
  if(i == mat.length - 1 && j == mat[0].length - 1) {
   if(sum == mat[i][j]) return 1;
   else return 0;
  }else {
   if(i >= mat.length || j >= mat[0].length)
    return 0;
   else {
    if(dp[i][j][sum-1] != -1) return  dp[i][j][sum-1];
    dp[i][j][sum-1] = this.pathCountHelper(mat, i+1, j, sum-mat[i][j])
      + this.pathCountHelper(mat, i, j+1, sum-mat[i][j]);
    return dp[i][j][sum-1];
   } 
  }
 }

Comments

Popular posts from this blog

MockInterview:785. Is Graph Bipartite?

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

94.Binary Tree Inorder Traversal