2011-04-28 79 views
1

对于DFS迷宫代在Java中,我想随机其中DFS的递归调用发生的顺序:的Java:随机化方法递归的调用顺序

for (int rows=i; rows<M; rows++) 
    for (int cols=j; cols<N; cols++){ 

      if(northValid) 
      { 
       DFS(iNorth,j); 
      } 

      if(southValid){ 
       DFS(iSouth,j); 
      } 

      if(eastValid){ 
       DFS(i, jEast); 
      } 

      if(westValid){ 
       DFS(i,jWest); 
      } 

我怎样才能做到这一点?

+0

你想随机选择一个'DFS('调用,或以随机顺序调用所有四个? – mellamokb 2011-04-28 21:33:18

回答

2

切换到Random类的呼叫:

Random r = new Random(); 
for (int rows=i; rows<M; rows++) 
    for (int cols=j; cols<N; cols++) { 
     bool found = false; 
     while (!found) 
      switch (r.next() % 4) { 
       case 0: if(northValid) { DFS(iNorth,j); found = true; } break; 
       case 1: if(southValid) { DFS(iSouth,j); found = true; } break; 
       case 2: if(eastValid) { DFS(i, jEast); found = true; } break; 
       case 3: if(westValid) { DFS(i, jWest); found = true; } break; 
      } 
    } 

需要注意的是,使用这种方法,你需要循环开关,直到遇到可用的墙,然后继续。这有点低效,但很简单。

0

伪代码:

for (int rows=i; rows<M; rows++) 
{ 
    for (int cols=j; cols<N; cols++) 
    { 
     // Generate a random number between 0 to 3 => %4 
     switch(randomNumber) 
     { 
      case 0: DFS(iNorth,j); 
        break; 
      // ... 

      case 3: DFS(i,jWest); 
        break; 

      default: break; 
     } 
    } 
} 
0

我结束了使用此:

Double lottery = Math.random(); 

     for (int rows=i; rows<M; rows++) 
      for (int cols=j; cols<N; cols++){ 


     if (lottery>=0.5D){ 
      if(northValid) 
      { 
       DFS(iNorth,j); 
      } 

      if(southValid){ 
       DFS(iSouth,j); 
      } 

      if(eastValid){ 
       DFS(i, jEast); 
      } 

      if(westValid){ 
       DFS(i,jWest); 
      } 


     } 

     else if (lottery<0.5D) 
     { 

      if(westValid){ 
       DFS(i,jWest); 
      } 

      if(eastValid){ 
       DFS(i, jEast); 
      } 

      if(southValid){ 
       DFS(iSouth,j); 
      } 

      if(northValid) 
      { 
       DFS(iNorth,j); 
      } 


     } 

效果很好,感谢您的答案。

+2

这怎么能工作?你只计算一个随机数? – 2011-04-28 22:09:51