-3

I have been trying to write a recursive backtracker using the given Wikipedia description of it but I can't grasp how to write it in java. Right now I have been using a double for-loop to go through all of the cells and using Math.random() to help pick a random neighbor. The problem is that I just don't know how to get the neighbor's index and add it to a stack. If someone could explain how to get the neighbor's index I think I would be able to finish the code.

  • Do you mean this? https://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_backtracker --- What have you tried? Show us. What is stopping you? Be *specific*. – Andreas Apr 22 '20 at 05:11

1 Answers1

0

In a two-dimensional array, a cell has potentially four neighbors. For example, here's a 4x4 grid:

     0   1   2   3
   -----------------
 0 |   |   | N |   |  
   -----------------
 1 |   | W | C | E |  
   -----------------
 2 |   |   | S |   |  
   -----------------
 3 |   |   |   |   |  
   -----------------

The cell marked "C" at position (x=2, y=1), row 1, has four neighbors, which I've labeled N, E, S, and W. If the cell at You obtain the neighbors by:

. The North neighbor is at position (x, y-1) . The East neighbor is at position (x+1, y) . The South neighbor is at position (x, y+1) . The West neighbor is at position (x-1, y)

You have to be careful, though, because if unguarded those calculations can cause you to index outside the bounds of the array. To check the directions you have to do something like this:

// check North neighbor
if (y > 0 && isNotOpen(a[y-1, x])) {
    ...
}

The y > 0 check prevents you from trying to check cell a[x, -1] when y == 0. You have to write similar checks for the other directions to prevent incorrect indexing.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351