Here is the DP question,
Given a ‘N’ * ’M’ maze with obstacles, count and return the number of unique paths to reach the right-bottom cell from the top-left cell. A cell in the given maze has a value ‘-1’ if it is a blockage or dead-end, else 0. From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only. Since the answer can be large, print it modulo 10^9 + 7.
For Example :
Consider the maze below :
0 0 0
0 -1 0
0 0 0
There are two ways to reach the bottom left corner –
(1, 1) -> (1, 2) -> (1, 3) -> (2, 3) -> (3, 3)
(1, 1) -> (2, 1) -> (3, 1) -> (3, 2) -> (3, 3)
Hence the answer for the above test case is 2.
**This is my solution using 2d Arrays.
**
import java.util.*;
public class Solution {
public static int f(int i, int j, ArrayList<ArrayList<Integer>> mat,int [][]dp){
if(i == 0 && j == 0)
return 1;
if((i < 0) || j < 0 || (mat.get(i).get(j)) == -1)
return 0;
if(dp[i][j] != -1)
return dp[i][j];
return dp[i][j] = f(i-1,j,mat,dp)%1000000007+f(i,j-1,mat,dp)%1000000007;
}
static int mazeObstacles(int n, int m, ArrayList<ArrayList<Integer>> mat) {
int dp[][] = new int[n][m];
// Initialize the dp array with -1
for (int row[] : dp)
Arrays.fill(row, -1);
return f(n-1,m-1,mat,dp)%1000000007;
}
}
This is my solution using 2d ArrayList:
import java.util.*;
public class Solution {
public static int f(int i, int j, ArrayList<ArrayList<Integer>> mat, ArrayList<ArrayList<Integer>> dp){
if(i == 0 && j == 0)
return 1;
if((i < 0) || j < 0 || (mat.get(i).get(j)) == -1)
return 0;
if(dp.get(i).get(j) != -1)
return dp.get(i).get(j);
return dp.get(i).set(j , f(i-1,j,mat,dp)%1000000007+f(i,j-1,mat,dp)%1000000007);
}
static int mazeObstacles(int n, int m, ArrayList<ArrayList<Integer>> mat) {
// Write your code here.
ArrayList<ArrayList<Integer>> dp = new ArrayList<>();
for (int i = 0; i < n; i++) {
ArrayList<Integer> row = new ArrayList<>();
for (int j = 0; j < m; j++) {
row.add(-1); // Add 0 to each column in the row
}
dp.add(row); // Add the row to the 2D ArrayList
}
return f(n-1,m-1,mat,dp)%1000000007;
}
}
I’m trying to initialize a 2d arrayList with -1 initially and based on that am accumulating my DP array.
pls help me where i went wrong when using 2d ArrayList.
Anonymous is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.