如何将此嵌套迭代转换为递归解决方案? [英] How do I convert this nested iteration to a recursive solution?

查看:195
本文介绍了如何将此嵌套迭代转换为递归解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个代码,计算矩阵中相邻元素的总和,并将它们存储到另一个 sum_mat 的矩阵中。我需要这个代码的相同结果,但在递归解决方案,我不知道如何将嵌套循环转换为递归。

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]; 
   }
}

结果示例:

n=3

     | 1   2    3  |       sum_mat=| 8   9 |
 mat=| 2   3    1  |  -->          | 11  7 |
     | 5   1    2  |        


推荐答案

尾递归过程和递归发起者:

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
}

p>

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...);
}

现在调用 for_loop_A 代替循环本身。继续转换,直到所有的循环都消失了。

Now call for_loop_A in place of the loop itself. Keep transforming like this until all the loops are gone.

这篇关于如何将此嵌套迭代转换为递归解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆