I just wanted to generate some mazes using the easiest algorithm, but all my mazes look like the following one:
Here is a piece of Java code (a whatVisit function works correct, don't look at it):
private void dfs(Point start, boolean[][] visited) {
Point nextCell = whatVisit(start, visited);
if(nextCell == null) // if there's nothing to visit
return;
// mark current cell as visited
visited[start.y][start.x] = true;
// destroy the wall between current cell and the new one
borders[(start.y + nextCell.y)/2][(start.x + nextCell.x)/2] = true;
// start a new search from found cell
dfs(nextCell, visited);
}
private Point whatVisit(Point p, boolean[][] visited) {
Vector<Point>cells = new Vector<Point>(); // to store acessible cells
// lookaround
if(p.x - 2 >= 0 && !visited[p.y][p.x - 2])
cells.add(new Point(p.x - 2, p.y));
if(p.x + 2 < visited[0].length && !visited[p.y][p.x + 2])
cells.add(new Point(p.x + 2, p.y));
if(p.y - 2 >= 0 && !visited[p.y - 2][p.x])
cells.add(new Point(p.x, p.y - 2));
if(p.y + 2 < visited.length && !visited[p.y + 2][p.x])
cells.add(new Point(p.x, p.y + 2));
// instead of Random
Collections.shuffle(cells);
// returns null if there are no acessible cells around
if(cells.size() > 0)
return cells.get(0);
else return null;
}
And I know why it doesn't work! When DFS finally come to the place where there are no accessible cells, it just going out back to start.
How to fix this and force to work correct?
Thanks.