Wednesday, 10 February 2010

A Maze Algorithm in Java

I had a good hunt around for a maze creator written in Java, but couldn't find one quite to my liking. So I wrote my own, using the Depth First - Recursive Backtracker method.

Download source my files here

First of all, I created a class that contains the details for each "cell" of the maze ( This contains the details required for each maze cell (which walls are up/down, and whether that cell has been visited yet).

Now on to the main code, my ( Hopefully, there's enough commenting on here to make it clear what it's doing, but just in case, here is the pseudo-code for the generateMaze() method:

  • Reset all cells in the grid ( resetGridCells() ).
  • Work out how many cells there are (width*height) and also create a last-in-first-out stack of visited cells.
  • Start at the top-left (y=0,x=0)
  • While there are still cells left unvisited (cellsVisited < width*height):
    • See if there are any cells that can be visited from the current cell that we have not yet visited ( unvisitedCellCanBeReached(...) ).
    • If there are cells we can visit, pick one at random ( getRandomUnvisitedCell(...) ), set the wall on the current side as down and move to the next cell. Add this next cell to the top of the stack, set it to "visited" and increase the visited count.
    • If there are no cells we can visit from our current location, then "pop" the previous location off the stack and move back there.
  • Once we've visited all the cells, I need to do a "cleanup". A slight flaw in my design means that if (say) a cells east wall is flagged as down (intact = false), then the cell next to it (on the east side) should have its west wall down (basically I've created double-strength walls). So the cleanup method knocks down any of these walls as well.
That's it. You can now call getGridCells() to get the array. If you want to try it out, download the MazeGenerator.jar file. It should auto-execute. It's got some other Java classes in there that I created quickly in Netbeans to allow a visual representation.

Have fun!