Java – given a 2D integer array, recursively find the path with the sum of the given number
Given a two-dimensional array, I need to recursively return a matrix whose path sum is a given number
The path matrix should be zero, but the sum of the paths is equal to the given number, which will be marked as 1
Path can only be in
I've tried all the possibilities. First check whether I've reached the next block
The problem is that after some iterations, it stops, does not return, and clears the block to 0. 0 again
private static boolean paintPath(int[][] mat,int sum,int[][] path,int i,int j){
if(sum<0)
return false;
path[i][j] = 1;
if(sum == 0)
return true;
printMat(path);
Sy@R_301_2354@.out.println();
if(withinBoundaries(mat,i+1,j) && path[i+1][j] != 1)
if(paintPath(mat,sum - mat[i][j],path,j))
return true;
if(withinBoundaries(mat,i,j+1) && path[i][j+1] != 1)
if(paintPath(mat,j+1))
return true;
if(withinBoundaries(mat,i-1,j) && path[i-1][j] != 1)
if(paintPath(mat,j))
return true;
if(withinBoundaries(mat,j-1) && path[i][j-1] != 1)
if(paintPath(mat,j-1))
return true;
path[i][j] = 0;
return false;
}
given
int[][] mat1 = {
{1,1,1},{5,100,{100,{1,1}
};
int[][] path = {
{0,0},{0,0}
};
And telephone
paintPath(mat1,5,0);
I hope the algorithm can return
{0,0}
I see
1 1 1 1
0 0 1 1
0 0 0 0
0 0 0 0
Replace
Then from the call to paintpath (mat1400,0); I expect
{0,0}
or
{0,0}
The problem is that my algorithm starts from (0,0) and finds the path from there. I need it to find any path from any starting point (no loop)
Edit: problems referenced in job: "We define the path in the array as a collection of adjacent cells. Adjacent cekks can be adjacent from left, right, top and bottom, but not diagonal. Each cell can only accumulate once in the path. Write a recursive method that accepts a 2D array mat, which contains integers greater than 0, an integer and positive number, and a 2D array path of the same size as mat
This method is required to check whether there are paths in the array whose sum of values is equal to sum If such a path exists, it should return true, false otherwize
Array paths are used to mark paths where the sum is equal to the sum
Path is 1 in the path cell and 0 in other cells
The method must be recursive and have no loops at all! Just like any other method you will write
You can use overloading
You can't change the mat