What's a good algorithm to generate a maze?

后端 未结 9 1482
囚心锁ツ
囚心锁ツ 2020-11-27 09:55

Say you want a simple maze on an N by M grid, with one path through, and a good number of dead ends, but that looks \"right\" (i.e. like someone made it by hand without too

9条回答
  •  失恋的感觉
    2020-11-27 10:26

    Recursive Backtracking is the easiest algorithm to implement.

    Here's a Java implementation:

    Here Cell is a class representing a cell in a 2D grid and cells is a 2D array of Cell objects. Cell has boolean variables top, bottom, left and right to indicate whether a cell has walls on these sides, a boolean variable visited to check whether we have traversed it and two integer variables row and col to indicate its position in the grid.

    Cell current = cells[0][0] , next;
        current.visited=true;
        do{
            next = getNeighbour(current);
            if(next!=null){
                removeWall(current , next);
                st.push(current);
                current = next;
                current.visited = true;
            }
            else {
                current = st.pop();
            }
        }
        while (!st.empty());
    
    
        private Cell getNeighbour(Cell cell){
        ArrayList ara = new ArrayList<>();
        if(cell.col>0 && !cells[cell.col-1][cell.row].visited)
             ara.add(cells[cell.col-1][cell.row]);
    
        if(cell.row>0 && !cells[cell.col][cell.row-1].visited)
             ara.add(cells[cell.col][cell.row-1]);
    
        if(cell.col0){
            return ara.get(new Random().nextInt(ara.size()));
        }else{
            return null;
        }
    }
    private void removeWall(Cell curr , Cell nxt){
        if((curr.col == nxt.col) && (curr.row == nxt.row+1)){/// top
            curr.top=nxt.botttom=false;
        }
        if(curr.col==nxt.col && curr.row == nxt.row-1){///bottom
            curr.botttom = nxt.top = false;
        }
        if(curr.col==nxt.col-1 && curr.row==nxt.row ){///right
            curr.right = nxt.left = false;
        }
        if(curr.col == nxt.col+1 && curr.row == nxt.row){///left
            curr.left = nxt.right = false;
        }
    }
    

提交回复
热议问题