如何将for循环转换为递归?

时间:2016-04-26 09:09:29

标签: c++ arrays class for-loop recursion

void FireSimulator::spread()
{
    int numberLoops;
    if(x>y)
        numberLoops=x;
    else
        numberLoops=y;

    for(int k=0; k<=numberLoops+1; k++)
   {
        for(int i=1; i<x-1; i++)
        {
            for(int j=1; j<y-1; j++)
            {
                if((forest[i][j].getState()==2) && (forest[i][j+1].getState()==1)) 
                    {
                        forest[i][j+1]=2;
                        Print();
                    }

                if((forest[i][j].getState()==2) && (forest[i+1][j].getState()==1)) 
                    {
                        forest[i+1][j]=2;
                        Print();
                    }

                if((forest[i][j].getState()==2) && (forest[i][j-1].getState()==1)) 
                    {
                        forest[i][j-1]=2;
                        Print();
                    }

                if((forest[i][j].getState()==2) && (forest[i-1][j].getState()==1)) 
                    {
                        forest[i-1][j]=2;
                        Print();
                    }           
            } 
    }  }
}

类FireSimulator模拟火灾蔓延。 A 2表示燃烧树,1表示树,0表示空点。该函数检查当前单元的邻居。如果树正在燃烧,并且旁边有一棵树,那么它旁边的树将会燃烧。它需要检查林中的所有单元格(数组)。我用3 for循环做了但是如何用递归做呢?

1 个答案:

答案 0 :(得分:1)

如果要获得完全相同的逻辑但没有循环,则需要使用递归函数替换每个循环。然后代替循环变量,你将有一个函数参数。并且不要忘记检查每个函数中的递归终止条件。我用快递替换了你的循环快速解决方案:

void CheckCellForIgnition(int col,int row) { // col and row designate a cell to check for ignition
    if (row < y - 1) {
        if ((forest[col][row]].getState() == 2) && (forest[col][row + 1].getState() == 1))
        {
            forest[col][row + 1] = 2;
            Print();
        }

        if ((forest[col][row].getState() == 2) && (forest[col + 1][row].getState() == 1))
        {
            forest[col + 1][row] = 2;
            Print();
        }

        if ((forest[col][row].getState() == 2) && (forest[col][row - 1].getState() == 1))
        {
            forest[col][row - 1] = 2;
            Print();
        }

        if ((forest[col][row].getState() == 2) && (forest[col - 1][row].getState() == 1))
        {
            forest[col - 1][row] = 2;
            Print();
        }
        CheckCellForIgnition(col, row + 1);
    }
}

void CheckColumnForIgnition(int col) { // col - column to check for ignition
    if (col < x - 1) {
        CheckCellForIgnition(col,1);
        CheckColumnForIgnition(col + 1);
    }
}

void IgniteIteration(int iterationsLeft) { // iterationsLeft - the number of iterations left to perform
    if (iterationsLeft>0) {
        CheckColumnForIgnition(1);
        IgniteIteration(iterationsLeft - 1);
    }
}

void spread()
{
    IgniteIteration(max(x, y));
}

执行逻辑应与循环代码完全相同。但是,如果您的火势蔓延逻辑没有那么修复,您可以考虑以另一种方式使用递归。