1

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

我怎样才能做到这一点?

4

3 回答 3

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

请注意,使用这种方法,您需要在交换机上循环,直到它碰到可用的墙,然后继续。这有点低效,但很简单。

于 2011-04-28T21:31:13.873 回答
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;
        }
    }
}
于 2011-04-28T21:34:11.687 回答
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);
            }


       }

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

于 2011-04-28T21:42:05.343 回答