Domen Lisjak
Domen Lisjak

Reputation: 11

Swift - Generate a random path

I am trying to create a simple maze, that will be based on a grid, 5x9 (for the iphone 5) The maze will be made with simple white squares(path) and black squares (the walls). How is it possible to generate a code that will make the path totally random, but will always be passable. Thanks in advance.

Upvotes: 0

Views: 1030

Answers (1)

Lucas
Lucas

Reputation: 21

Consider an NxN grid of cells, each of which initially has a wall between it and its four neighbouring cells. For each cell (x, y), maintain a variable up[x,y] that is true if there is wall separating (x, y) and (x, y + 1). Maintain analogous variables left[x, y], down[x,y], and right[x,y] for the corresponding walls.

Note that if there is a wall above (x, y) then up[x,y] = down[x,y+1] = true. Construct the maze by knocking down some of the walls as follows:

  1. Start at the lower level cell (1, 1).
  2. Find a neighbour at random that you haven't yet been to.
  3. If you find one, move there, knocking down the wall. If you don't find one, go back to the previous cell.
  4. Repeat steps 2 and 3 until you've been to every cell in the grid.

Source: http://algs4.cs.princeton.edu/41undirected/

A Swift implementation can be found at: https://github.com/lucaslouca/swift-mazes

Upvotes: 1

Related Questions