Using a stack to traverse and solve a maze - Java

爱⌒轻易说出口 提交于 2019-12-05 08:47:18
Greg

Are you sure your algorithm would solve any maze? I think it would get stuck in this simple mock-up (where S is start and F is finish):

xxxxxxxxxx
Sooooooxxx
xxxxxxoxxx
xxxxxxFxxx

Your algorithm would proceed down the first hall until it faced the fall, turn left, be facing the "north" wall, turn left again, and walk back down the first hallway, where it would turn left twice again and keep repeating this problem.

The the right-hand rule algorithm (see the wikipedia page, as well as other sections for more maze algs) should do solve any maze without loops, and should be fairly easy to implement in java.

You could use a

Stack<Point> points = new Stack<>();

// add a point
Point p = new Point(x, y);
if (points.contains(p))
   // been here before, in circles.
else
   points.add(p);

For the algorithm portion, a depth first recursion through the stack is preferred. Something along the lines of:

currentSpot = (0,0)  // The starting point //

while(! currentSpot.isExit()) {

  if (! currentSpot.left().isWall()) stack.push(currentSpot.left());
  if (! currentSpot.forward().isWall()) stack.push(currentSpot.forward());
  if (! currentSpot.right().isWall()) stack.push(currentSpot.right());

  currentSpot = stack.pop();  // Get the next location //
}

You'll want your point class to return the next point in each given direction (except backward), as well as detect when you'd be at the edges of the maze. You'll probably want a Maze class that contains all of the points, does the printing, stores the X/O, etc. So, you could probably replace the initial currentSpot = (0,0) with currentSpot = Maze.getStartingSpot();

For your algorithm, you do not need a stack. Only if you use backtracking to undo traversal decision, you would need a stack.

For the algorithm you could use backtracking (EDIT although it doesn't quite match your general idea.) You just have to realize your movements are "pushed" into a virtual stack, and they must be unpushed (and therefore undone.) You might have to implement the stack yourself if the "robot" is an actually moving object, but you can rely on the call stack if you just want to solve the maze.

We tackled this problem once when I was in school and we used a solution similar to the right/left hand rule. I believe we did this while learning about Linked Lists. In a nutshell, the algorithm was like this:

  1. Go left. If possible, repeat.
  2. If not, go straight. If possible, return to step 1.
  3. If not, go right. If possible, return to step 1.

At each step, you also check to see if the spot you are standing on is the finish. If you are unable to continue (ie, not able to go left, straight, or right), you then mark the spot you are standing on as 'visited' and back up. Rinse and repeat.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!