I understand what tail recursion is but I am having trouble converting this method to tail recursion. I am trying to count how many adjacent elements there are in a matrix. Therefore, my question is how would you turn this into a tail recursion?
public static int ExploreAndLabelColony(char[][] grid, int i, int j, char c,int count) {
grid[i][j] = c;
count = 1;
if ((i>0 && i<grid.length && j<grid[0].length) && (grid[i-1][j] == '1')) { //vertical bottom
count +=ExploreAndLabelColony(grid, i-1,j,c,count);
}
if (i+1<grid.length && j<grid[0].length && grid[i+1][j] == '1') { //vertical top
count+=ExploreAndLabelColony(grid, i+1,j ,c,count);
}
if (j>0 && i<grid.length && j<grid[0].length && grid[i][j-1] == '1') { //horizontal left
count +=ExploreAndLabelColony(grid, i,j-1 ,c,count);
}
if (i<grid.length && j+1<grid[0].length && grid[i][j+1] == '1') { //horizontal right
count+=ExploreAndLabelColony(grid, i,j+1 ,c,count);
}
if (i+1<grid.length && j+1<grid[0].length && grid[i+1][j+1] == '1') { //diagonal bottom right
count+=ExploreAndLabelColony(grid, i+1,j+1 ,c,count);
}
if (j>0 && i+1<grid.length && j<grid[0].length && grid[i+1][j-1] == '1') { //diagonal bottom right
count+=ExploreAndLabelColony(grid, i+1,j-1 ,c,count);
}
if (i>0 && i<grid.length && j+1<grid[0].length && grid[i-1][j+1] == '1') { //diagonal top right
count+=ExploreAndLabelColony(grid, i-1,j+1 ,c,count);
}
if (i>0 && j>0 && i<grid.length && j<grid[0].length && grid[i-1][j-1] == '1') { //diagonal top left
count+=ExploreAndLabelColony(grid, i-1,j-1 ,c,count);
}
return count;
}
Read more here: https://stackoverflow.com/questions/66266432/how-to-convert-to-tail-recursion
Content Attribution
This content was originally published by cs777 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.