首页 > 解决方案 > 递归除法迷宫 Java

问题描述

我在完成基于此链接的算法时遇到问题。在建造了一堵墙后,我选择了迷宫的上部或左侧,它似乎只在需要中断递归并进入另一个划分方法调用的地步才创建自己。我不确定我是否理解需要正确传递给最后一次调用divide方法的值。

    public void divide(int x, int y, int width, int hight) {
        if (width< 2 || hight< 2) ;  

        else {
            boolean horizontal = chooseOrientation(width,hight);

            if (horizontal) {
                int randomNumber = r.nextInt(hight - 1);
                wallY = randomNumber + y;

                for (int i = x; i < width; i++) {                       
                    fields[wallY][i].setHorizontalWall();
                }
                fields[wallY][r.nextInt(width- 1)].deleteHorizontalWall();   
                hight = wallY - y + 1;
                divide(x, y, width, hight);
            }

            else {
                int randomNumber = r.nextInt(width- 1);
                WallX = randomNumber + x;

                for (int i = y; i < hight; i++) {
                    fields[i][WallX].setVerticalWall();
                }
                fields[r.nextInt(hight - 1) + y][WallX].deleteVerticalWall();
                width = WallX - x + 1;
               }

            if(horizontal){
                hight = y + hight + WallY-1;
                y = WallY + 1;
            }
            else {
                width = WallX - 1 + width + x;
                x = WallX + 1;
            }
            divide(x, y, width, hight);
        }
    }

标签: javaalgorithmmaze

解决方案


在“递归除法”算法中,您从一个完整的二维网格图开始,然后开始移除以水平和垂直“条纹”交替的边缘(= 构建“墙”)。在每个“条纹”中,只剩下一个边缘(“门”)。

可以在此处找到该算法的基于图形的版本:

https://github.com/armin-reichert/mazes

https://github.com/armin-reichert/mazes/blob/master/mazes-algorithms/src/main/java/de/amr/maze/alg/others/RecursiveDivision.java


推荐阅读