How do I convert this nested iteration to a recursive solution?

匿名 (未验证) 提交于 2019-12-03 09:18:39

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!