在Java中通过递归检查数组中是否存在路径的总和为sum

时间:2019-06-02 20:29:56

标签: java arrays recursion

我正在尝试编写下一个程序:

仅包含正整数的二维正方形数组。 每个单元只能在路径上出现一次,编写一个递归布尔静态方法,该方法接受包含数字(其中大于零)和任何正和的二维二维数组作为参数,该方法作为参数给出与mat大小相同的二维数组,它应检查数组中总和为sum的路径。否则,将返回false值,并且该路径用于标记路径总和:最初,当将路径数组作为参数传递时,其所有单元格都包含总和。在方法的结尾(如果有)在mat数组的总和中,路径数组将在参与该路径的单元格中包含1,在所有其他单元格中包含0.如果mat数组中没有此类路径,则如果存在,则该路径数组应包含值0多个路径一个总和,数组路径将包含路径总和之一(任意)。例如,给定数组mat如下:

enter image description here

总和4,该方法返回true,并且path数组可以是以下三个数组之一:

enter image description here

我尝试过:

public static boolean findSum(int i, int j, int mat[][], int sum, int path[][]){
    if(sum == 0) {
        return true;
    }else if(sum < 0) {
        return false;
    }else if (i < mat.length - 1 && findSum(i + 1, j, mat, sum - mat[i][j], path)) {
            path[i][j] = 1;
            return true;
    }else if (i < mat.length - 1 && findSum(i + 1, j, mat, sum, path))
            return true;
    else if (j < mat.length - 1 && findSum(i, j + 1, mat, sum - mat[i][j], path)) {
            path[i][j] = 1;
            return true;
    }else if (j < mat.length - 1 && findSum(i, j + 1, mat, sum, path))
            return true;
    return false;
}



public static boolean findSum (int mat[][], int sum, int path[][]){
    if(findSum(0,0, mat, sum, path)) {
        System.out.println(Arrays.deepToString(path));
        return true;
    }else {
        return false;
    }
}

然后我得到了

1 | 0 | 0 | 0
1 | 0 | 0 | 0
1 | 0 | 0 | 0
0 | 0 | 0 | 0

问题是我的路径太长,只有2条路径

1 个答案:

答案 0 :(得分:0)

假设您的算法正确,我相信您传递的2D路径数组始终会引用相同的数组。因此,当元素一次设置为1时,数组的后续用法也总是将该元素也设置为1。解决此问题的最简单方法是执行类似的操作(未选中语法)

    int[][] tempPath= new int[path.length()][path[0].size()];

    tempPath= path;