The Count All Possible Paths problem in a grid is a classic dynamic programming problem that asks to count all possible paths from the top-left corner to the bottom-right corner of a given grid.
One approach to solving this problem using dynamic programming is to build a two-dimensional array dp[][] to store the number of paths to reach each cell of the grid. The approach is to fill in this array row by row and column by column, where each value of dp[i][j] represents the number of paths to reach that cell from the top-left corner.
The base case for the array is when we can only move either right or down. In this case, there is only one way to reach any cell in the first row or first column. Thus, we can initialize the first row and first column of the array to 1.
After initialization, we can fill the rest of the array by summing up the number of paths to reach the current cell from the cell above it and the cell to the left of it, i.e., dp[i][j] = dp[i-1][j] + dp[i][j-1]. This is because we can only move either right or down.
Finally, the value of dp[m-1][n-1] represents the total number of paths from the top-left corner to the bottom-right corner of the grid.
Here’s the Java implementation of the Count All Possible Paths problem in a grid using dynamic programming:
public int countPaths(int m, int n) {
int[][] dp = new int[m][n];
// initialize first row to 1
for (int i = 0; i < n; i++) {
dp[0][i] = 1;
}
// initialize first column to 1
for (int j = 0; j < m; j++) {
dp[j][0] = 1;
}
// fill the rest of the array
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
// return the total number of paths
return dp[m-1][n-1];
}
For example, if we call ‘countPaths(3,3)‘, we get the output ‘6‘, which means there are 6 possible paths from the top-left corner to the bottom-right corner of a 3x3 grid. Here’s a visualization of the grid and the paths:
1 1 1
1 2 3
1 3 6
Possible paths:
1. (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2)
2. (0,0) -> (1,0) -> (2,0) -> (2,1) -> (2,2)
3. (0,0) -> (0,1) -> (1,1) -> (1,2) -> (2,2)
4. (0,0) -> (1,0) -> (1,1) -> (1,2) -> (2,2)
5. (0,0) -> (0,1) -> (1,1) -> (2,1) -> (2,2)
6. (0,0) -> (1,0) -> (2,0) -> (2,1) -> (2,2)