问题
I have this code I wrote that calculates the sum of neighboring elements in a matrix and stores them into another matrix called sum_mat. I need the same result of this code but in a recursive solution and I don't know how to convert nested loops into recursion.
void calculate_result(int n,int mat[100][100])
{
//calculates an (n-1)x(n-1) matrix in which each element the sum of 4
// neighboring elements in the original matrix.
int sum_mat[100][100];
for(int i=1;i<=n-1;i++)
{
for(int j=1;j<=n-1;j++)
sum_mat[i][j]=mat[i][j]+mat[i+1][j]+mat[i][j+1]+mat[i+1][j+1];
}
}
An example of the result:
n=3
| 1 2 3 | sum_mat=| 8 9 |
mat=| 2 3 1 | --> | 11 7 |
| 5 1 2 |
回答1:
You can convert any "for i" loop into a tail recursive procedure and a recursion initiator:
// loop A
for (i = 1; i <= n; i++) {
// body code
}
becomes
void for_loop_A_impl(int i, ...params needed by the body...) {
if (i > n) return;
// body code
for_loop_A_impl(i + 1,...params needed by the body...);
}
void for_loop_A(...params needed by the body code...) {
for_loop_A_impl(1, ...params needed by the body code...);
}
Now call for_loop_A in place of the loop itself. Keep transforming like this until all the loops are gone.
来源:https://stackoverflow.com/questions/25109518/how-do-i-convert-this-nested-iteration-to-a-recursive-solution