使用java

时间:2016-05-23 10:49:13

标签: java

尝试使用Arrays.fill方法分配默认值,但我得到了ArrayStoreException。代码如下所示“用于查找仅在k次移动的2d数组中从源到目的地的所有路径”

我浏览了几个链接(https://stackoverflow.com/questions/15120089/convert-arraylist-to-array-throws-java-lang-arraystoreexception,https://stackoverflow.com/questions/12369957/dealing-with-an-arraystoreexception),但无法找到问题

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);
    }
}

1 个答案:

答案 0 :(得分:0)

您遇到此错误,因为您已在此行中将dp声明为Multidimentional数组

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

这意味着您将拥有一个数组数组,然后您尝试使用Arrays.fill()将值赋予此数组,这会在此行中引发错误

Arrays.fill(dp,-1);

它抛出一个异常,因为fill方法试图影响一个整数&#34; -1&#34;到dp数组的每个元素,虽然dp是一个数组数组而不是整数数组,这正是异常的原因,

相关问题