I wrote in an exam a backtracking code that moving between cell and counting paths, the conditions are if the next cell is i+k or j+k or i-k or j-k. the code somehow is still going out of bounds even due I tried to prevent it from doing so.
I tried adding fixing the code by adding +1 in the checking valid move in the "if" conditions.
public class Test3
{
public static int howManyPaths(int [][] mat)
{
return howManyPaths(mat,0,0,0);
}
private static int howManyPaths(int [][] mat, int i, int j, int count)
{
if(i == mat.length-1){return count;}
if(j == mat[i].length-1){return howManyPaths(mat,i+1,0,count);}
count = pathCount(mat,i,j);
return howManyPaths(mat,i,j+1,count);
}
private static int pathCount(int [][] mat, int i, int j)
{
int k = mat[i][j];
if(i < mat.length-1 && mat[i][j] == mat[i+k][j] && i+k < mat.length-1){
return 1 + pathCount(mat,i+k,j);}
if(j < mat[i].length-1 && mat[i][j]==mat[i][j+k] && j+k < mat[i].length-1){
return 1 + pathCount(mat,i,j+k);}
if(i > 0 && mat[i][j]==mat[i-k][j] && i-k > 0){
return 1 + pathCount(mat,i-k,j);}
if(j > 0 && mat[i][j]==mat[i][j-k] && j-k > 0){
return 1 + pathCount(mat,i,j-k);}
return 1;
}
}
the expected is how many paths and the actual results are "out of bounds".
Edited with the fixet code still not working