What's a good algorithm to generate a maze?

后端 未结 9 1517
囚心锁ツ
囚心锁ツ 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:19

    Here's the DFS algorithm written as pseudocode:

    create a CellStack (LIFO) to hold a list of cell locations
    set TotalCells = number of cells in grid
    choose a cell at random and call it CurrentCell
    set VisitedCells = 1

    while VisitedCells < TotalCells find all neighbors of CurrentCell with all walls intact
    if one or more found choose one at random
    knock down the wall between it and CurrentCell
    push CurrentCell location on the CellStack
    make the new cell CurrentCell
    add 1 to VisitedCells else pop the most recent cell entry off the CellStack
    make it CurrentCell endIf endWhile

提交回复
热议问题