Guest User

Untitled

a guest
Jan 6th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.90 KB | None | 0 0
  1. public class MazeSolver {
  2.  
  3. public int counter = 0;
  4. Maze maze;
  5.  
  6. public MazeSolver(Maze maze) {
  7. this.maze = maze;
  8. }
  9.  
  10. public int shortestPath() {
  11.  
  12. int DistanceFromStart = Integer.MAX_VALUE;
  13. Queue<Point> Q = new Queue<Point>();
  14. //set current to the DistanceFromStart of the maze
  15. Point current = new Point(0,0); //keeps track of current position
  16. //add DistanceFromStart of maze to queue
  17. Q.enqueue(current);
  18. while (!Q.isEmpty()) {
  19. boolean canMove = false;
  20. current = Q.dequeue();
  21. DistanceFromStart = maze.getCell(current.x, current.y);
  22.  
  23. //keeps track of distance from the start of the maze
  24. if (current.x == maze.getWidth() - 1 && current.y == maze.getHeight() - 1) {
  25. maze.setCell(0, 0, 0);
  26. maze.setAsPassable(true);
  27. break;
  28. }
  29.  
  30. //checks for valid moves, enqueues if it is tried to find goal through that path
  31. //go up
  32. if (current.y > 0 && !maze.getHorizontalWall(current.x, current.y) && maze.getCell(current.x, current.y - 1) == 0)
  33. {
  34. maze.setCell(current.x, current.y - 1, DistanceFromStart + 1);
  35. Point p = new Point(current.x, current.y - 1);
  36. Q.enqueue(p);
  37. }
  38. //go down
  39. if (current.y < maze.getHeight() - 1 && !maze.getHorizontalWall(current.x, current.y + 1) && maze.getCell(current.x, current.y + 1) == 0)
  40. {
  41. maze.setCell(current.x, current.y + 1, DistanceFromStart + 1);
  42. Point p = new Point(current.x, current.y + 1);
  43. Q.enqueue(p);
  44. }
  45. //go left
  46. if (current.x > 0 && !maze.getVerticalWall(current.x, current.y) && maze.getCell(current.x - 1, current.y) == 0)
  47. {
  48. maze.setCell(current.x - 1, current.y, DistanceFromStart + 1);
  49. Point p = new Point(current.x - 1, current.y);
  50. Q.enqueue(p);
  51. }
  52. //go right
  53. if (current.x < maze.getWidth() - 1 && !maze.getVerticalWall(current.x + 1, current.y) && maze.getCell(current.x + 1, current.y) == 0)
  54. {
  55. maze.setCell(current.x + 1, current.y, DistanceFromStart + 1);
  56. Point p = new Point(current.x + 1, current.y);
  57. Q.enqueue(p);
  58. }
  59. }
  60. return DistanceFromStart;
  61. }
  62.  
  63. }
  64.  
  65. class Point {
  66.  
  67. int x;
  68. int y;
  69.  
  70. Point(int x, int y) {
  71. this.x = x;
  72. this.y = y;
  73. }
  74.  
  75. //Prints path
  76. public String toString() {
  77. return "[" + x + ", " + y + "]";
  78. }
  79. }
Add Comment
Please, Sign In to add comment