1

What is the best algorithm to generate a maze in a grid?

I have heard of Kruskal's algorithm and the recursive backtracker amongst other but both of these rely on walls.What would be the best algorithm to create amaze where one entire cell is a wall?

user2592835
  • 1,547
  • 5
  • 18
  • 26

1 Answers1

4

Modifying recursive backtracking or Prim's algorithm should be simple enough (code derived from Wikipedia)

Randomized Prim's algorithm

  • Start with a grid of filled cells.
  • Pick a cell, mark it as part of the maze. Add the surrounding filled cells of the cell to the cell list.
  • While there are cells in the list:
    • Pick a random cell from the list. If the cell doesn't have 2 explored neighbours:
      • Clear the cell.
      • Add the neighbouring filled cells to the cell list.
    • Remove the cell from the list.
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • Could you give an example in python? Mine seems just to rapidly increase the number of cells in the cell list. – user2592835 May 28 '14 at 10:51
  • I'm unfortunately not particularly familiar with Python. The number of cells should rapidly increase (at the beginning), but one cell should be removed at every iteration of the while-loop and never added to it again - make sure both of these are true. – Bernhard Barker May 29 '14 at 14:26
  • Ah, I think my problem is that my if conditions allowed previously used walls to be added to the list. – user2592835 May 29 '14 at 15:19
  • What do you refer to when you mean "explored"? – user2592835 May 29 '14 at 16:05
  • I believe that should be synonymous with "cleared" in this case. – Bernhard Barker May 29 '14 at 21:53
  • Should the edges of the maze link together? For example, at cell 9,9, would cell 0,0 become a neighbour (on a 10x10 grid)? – user2592835 May 30 '14 at 09:03
  • If you want it to wrap around (i.e. be able to move from a left-most cell to a right-most, or top-most to bottom-most, in a single move), then yes, otherwise, no. Although moving from 9,9 (bottom-right) to 0,0 (top-left) doesn't seem like a valid move, even allowing wrap-around - perhaps you meant 9,9 (bottom-right) to 9,0 (top-right), or 9,9 to 0,9 (bottom-left). – Bernhard Barker May 30 '14 at 12:55
  • Ah, I suddenly see the confusion.When you referred to "neighbour" you considered adjacent rectangles but when I thought of "neighbour" I considered neighbours in the context of game of life- where diagonals are acceptable. – user2592835 May 30 '14 at 15:09
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/54807/discussion-between-user2592835-and-dukeling). – user2592835 May 30 '14 at 16:06