Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. public class MazeSolver {
  2. public static String findPath(Maze maze) {
  3. //Keep track of locations visited, defaults to all false values
  4. boolean[][] visited = new boolean[maze.getNumRows()][maze.getNumCols()];
  5.  
  6. //This stack should contain a list of adjacent locations to get from entry to exit
  7. Stack<MazeLocation> solution = new StackRefBased<MazeLocation>();
  8. solution.push(maze.getEntry());
  9. String result = "";
  10.  
  11. try {
  12. //Keep looking for a path to the exit until we reach the exit, or are out of options
  13. while (!solution.isEmpty() && !solution.peek().equals(maze.getExit())) {
  14. MazeLocation current = solution.peek();
  15. visited[current.getRow()][current.getCol()] = true;
  16.  
  17. //Attempt to move right, then down, then left, then up, but only if it isn't visited yet
  18. if (!maze.isWall(current.getRow(), current.getCol() + 1) && !visited[current.getRow()][current.getCol() + 1]) {
  19. //Move right
  20. solution.push(new MazeLocation(current.getRow(), current.getCol() + 1));
  21. } else if (!maze.isWall(current.getRow() + 1, current.getCol()) && !visited[current.getRow() + 1][current.getCol()]) {
  22. //Move down
  23. solution.push(new MazeLocation(current.getRow() + 1, current.getCol()));
  24. } else if (!maze.isWall(current.getRow(), current.getCol() - 1) && !visited[current.getRow()][current.getCol() - 1]) {
  25. //Move left
  26. solution.push(new MazeLocation(current.getRow(), current.getCol() - 1));
  27. } else if (!maze.isWall(current.getRow() - 1, current.getCol()) && !visited[current.getRow() - 1][current.getCol()]) {
  28. //Move up
  29. solution.push(new MazeLocation(current.getRow() - 1, current.getCol()));
  30. } else {
  31. //No new locations to move to, so backtrack
  32. solution.pop();
  33. }
  34. }
  35.  
  36. //The solution stack now contains a solution, or it is empty and the maze is not solvable.
  37. while (!solution.isEmpty()) {
  38. result = solution.pop() + result;
  39. if (!solution.isEmpty()) {
  40. result = " " + result;
  41. }
  42. }
  43.  
  44. } catch (StackEmptyException e) {
  45. System.out.println(e);
  46. }
  47.  
  48. return result;
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement