Java:随机化方法递归调用的顺序

时间:2011-04-28 21:29:11

标签: java random depth-first-search maze

对于Java中的DFS迷宫生成,我想随机化DFS的递归调用的顺序:

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

我该怎么做?

3 个答案:

答案 0 :(得分: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;
            }
    }

请注意,使用此方法,您需要遍历交换机,直到它到达可用的墙,然后继续。这有点低效,但非常简单。

答案 1 :(得分: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;
        }
    }
}

答案 2 :(得分: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);
            }


       }

工作得很好,谢谢你的答案。