Skip to content

Commit 38823ef

Browse files
authored
Create #PathsInMatrixWithGivenCost.java
1 parent e55b769 commit 38823ef

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
https://www.techiedelight.com/counting-paths-on-grid-to-reach-destination-cell/
3+
https://www.geeksforgeeks.org/number-of-paths-with-exactly-k-coins/
4+
5+
6+
pathCount(m, n, k): Number of paths to reach mat[m][n] from mat[0][0]
7+
when cost = k
8+
9+
If (m == 0 and n == 0)
10+
return 1 if mat[0][0] == k else return 0
11+
Else:
12+
pathCount(m, n, k) = pathCount(m-1, n, k - mat[m][n]) +
13+
pathCount(m, n-1, k - mat[m][n])
14+
15+
Normal Recursion
16+
*/
17+
18+
public int pathCount(int A[][], int row, int col, int cost){
19+
//Base Case
20+
if(cost<0) return 0;
21+
//Base Case --> Valid path
22+
else if(row==0 && col==0 && cost == A[0][0]) return 1;
23+
//Base Case
24+
else if(row==0 && col==0 && cost != A[0][0]) return 0;
25+
26+
//First row --> Only one move --> Go left
27+
else if(row == 0) return pathCount(A, row, col-1, cost-A[row][col]);
28+
29+
//First col --> Only one move --> Go up
30+
else if(col == 0) return pathCount(A, row-1, col, cost-A[row][col]);
31+
32+
//Cosider both --> up and left
33+
else return pathCount(A, row-1, col, cost-A[row][col]) + pathCount(A, row, col-1, cost-A[row][col]);
34+
}
35+
36+
//Memoized Recursion - using a hashmap
37+
38+
public int pathCount(int A[][], int row, int count, int cost, HashMap<String, Integer> map){
39+
if(cost<0) return 0;
40+
41+
else if(row==0 && col==0 && cost == A[0][0]) return 1;
42+
43+
else if(row==0 && col==0 && cost != A[0][0]) return 0;
44+
45+
String key = row+"|"+col+"|"+cost;
46+
47+
if(!map.containsKey(key)){
48+
else if(row == 0) map.put(key, pathCount(A, row, col-1, cost-A[row][col]));
49+
50+
else if(col == 0) map.put(key, pathCount(A, row-1, col, cost-A[row][col]));
51+
52+
else map.put(key, pathCount(A, row-1, col, cost-A[row][col]) + pathCount(A, row, col-1, cost-A[row][col]));
53+
}
54+
return map.get(key);
55+
}
56+
57+
//Memoized recursion - using an 3d array
58+
59+
public int pathCount(int A[][], int row, int col, int cost, int dp[][]){
60+
if(cost<0) return 0;
61+
62+
else if(row==0 && col==0 && cost == A[0][0]) return 1;
63+
64+
else if(row==0 && col==0 && cost != A[0][0]) return 0;
65+
66+
else if(dp[row][col][cost] != -1) return dp[row][col][cost];
67+
else{
68+
dp[row][col][cost] = pathCount(A, row-1, col, cost-A[row][col]) + pathCount(A, row, col-1, cost-A[row][col]);
69+
70+
return dp[row][col][cost];
71+
}
72+
}
73+
74+
//Time Complexity of DP solution - O(n*m*cost)
75+
//This is Psedo-Polynomial Time

0 commit comments

Comments
 (0)