1

trying to assign default value using Arrays.fill method, but I'm getting ArrayStoreException. Code is given Below "for finding all path from source to destination in 2d array with only k moves"

I went through few links(https://stackoverflow.com/questions/15120089/convert-arraylist-to-array-throws-java-lang-arraystoreexception,https://stackoverflow.com/questions/12369957/dealing-with-an-arraystoreexception), but not able to locate the problem

public class FindPathWithConstaint {
    int[][][][] dp = new int[100][100][100][2];
    public static void main(String arg[]) {
        int m = 3, n = 3, k =2;
        FindPathWithConstaint obj = new FindPathWithConstaint();
        System.out.println(obj.findAllPath(m,n,k));     
    }

    public int findAllPath(int m, int n, int k) {       
        if(m==0 && n==0)
            return 1;
        Arrays.fill(dp,-1);
        return countAllPaths(m-1,n,k,1) + countAllPaths(m,n-1,k,0);     
    }

    public int countAllPaths(int i, int j, int k, int d) {
        if(i<0 || j<0)
            return 0;
        if(i==0 && j==0)
            return 1;
        if(k==0) {
            if(d==0 && i==0)
                return 1;
            if(d==1 && j==0)
                return 1;
        }
        if(dp[i][j][k][d]!=-1)
             return dp[i][j][k][d];
        if(d==0)
            return countAllPaths(i,j-1,k,0) + countAllPaths(i-1,j,k-1,1);
        else
            return countAllPaths(i-1,j,k,1) + countAllPaths(i,j-1,k-1,0);
    }
}
0

1 Answer 1

0

You are Having this error because you have declared dp as Multidimentional array in this line

int[][][][] dp = new int[100][100][100][2];

Which mean that you gonna have an array of arrays, then you have tried to assigne values to this array using Arrays.fill() which throws error in this line

Arrays.fill(dp,-1);

it throws an exception because the fill method try to affect an integer "-1" to each element of dp array, although dp is an array of arrays not an array of integers and that is exactly the cause of the exception,

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for noticing the cause, problem solved

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.