Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MazeSolver {
- public int counter = 0;
- Maze maze;
- public MazeSolver(Maze maze) {
- this.maze = maze;
- }
- public int shortestPath() {
- int DistanceFromStart = Integer.MAX_VALUE;
- Queue<Point> Q = new Queue<Point>();
- //set current to the DistanceFromStart of the maze
- Point current = new Point(0,0); //keeps track of current position
- //add DistanceFromStart of maze to queue
- Q.enqueue(current);
- while (!Q.isEmpty()) {
- boolean canMove = false;
- current = Q.dequeue();
- DistanceFromStart = maze.getCell(current.x, current.y);
- //keeps track of distance from the start of the maze
- if (current.x == maze.getWidth() - 1 && current.y == maze.getHeight() - 1) {
- maze.setCell(0, 0, 0);
- maze.setAsPassable(true);
- break;
- }
- //checks for valid moves, enqueues if it is tried to find goal through that path
- //go up
- if (current.y > 0 && !maze.getHorizontalWall(current.x, current.y) && maze.getCell(current.x, current.y - 1) == 0)
- {
- maze.setCell(current.x, current.y - 1, DistanceFromStart + 1);
- Point p = new Point(current.x, current.y - 1);
- Q.enqueue(p);
- }
- //go down
- if (current.y < maze.getHeight() - 1 && !maze.getHorizontalWall(current.x, current.y + 1) && maze.getCell(current.x, current.y + 1) == 0)
- {
- maze.setCell(current.x, current.y + 1, DistanceFromStart + 1);
- Point p = new Point(current.x, current.y + 1);
- Q.enqueue(p);
- }
- //go left
- if (current.x > 0 && !maze.getVerticalWall(current.x, current.y) && maze.getCell(current.x - 1, current.y) == 0)
- {
- maze.setCell(current.x - 1, current.y, DistanceFromStart + 1);
- Point p = new Point(current.x - 1, current.y);
- Q.enqueue(p);
- }
- //go right
- if (current.x < maze.getWidth() - 1 && !maze.getVerticalWall(current.x + 1, current.y) && maze.getCell(current.x + 1, current.y) == 0)
- {
- maze.setCell(current.x + 1, current.y, DistanceFromStart + 1);
- Point p = new Point(current.x + 1, current.y);
- Q.enqueue(p);
- }
- }
- return DistanceFromStart;
- }
- }
- class Point {
- int x;
- int y;
- Point(int x, int y) {
- this.x = x;
- this.y = y;
- }
- //Prints path
- public String toString() {
- return "[" + x + ", " + y + "]";
- }
- }
Add Comment
Please, Sign In to add comment