[英]How to convert to tail recursion
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;
}
This might qualify as tail recursion:这可能符合尾递归:
static class Queue {
int i;
int j;
Queue next;
Queue(int i, int j, Queue next) {
this.i = i;
this.j = j;
this.next = next;
}
}
int exploreAndLabel(char[][] grid, int i, int j, char c) {
return exploreAndLabel(new Queue(i, j, null), grid, c, 0);
}
int exploreAndLabel(Queue queue, char[][] grid, char c, int count) {
if (queue == null) {
return count; // no more work
}
int i = queue.i;
int j = queue.j;
queue = queue.next;
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {
// outside grid
} else if (grid[i][j] != '1') {
// outside colony
} else {
grid[i][j] = c; // label
count++;
queue = new Queue(i - 1, j - 1, queue);
queue = new Queue(i - 1, j, queue);
queue = new Queue(i - 1, j + 1, queue);
queue = new Queue(i, j - 1, queue);
queue = new Queue(i, j + 1, queue);
queue = new Queue(i + 1, j - 1, queue);
queue = new Queue(i + 1, j, queue);
queue = new Queue(i + 1, j + 1, queue);
}
return exploreAndLabel(queue, grid, c, count);
}
and here is a test:这是一个测试:
@Test
public void testTailRecursion() {
char[][] grid = Stream.of(
"00000101",
"00001101",
"00111010")
.map(String::toCharArray)
.toArray(char[][]::new);
int count = exploreAndLabel(grid, 2, 3, '2');
Assert.assertEquals(9, count);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.