2016-04-26 132 views
-1
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循环做了它,但如何用递归做到这一点?如何将循环转换为递归?

+0

考虑接受x/y坐标来检查的函数。检查指定的单元格,然后为每个邻居调用与邻居坐标相同的函数。 – kicken

回答

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

执行逻辑应该是完全一样与你的循环代码。但是,如果你的火力传播逻辑不是很固定的话,你可以考虑以另一种方式使用递归。