import java.util.PriorityQueue; public class PQMaze extends Maze { public PQMaze(int rows, int cols){ super (rows, cols); } @Override public void solveMaze(){ PriorityQueue queue = new PriorityQueue(); //starting maze position MazePosition start = new MazePosition(0,0,0, null); //this will be set when we get to the finish MazePosition finish = null; //put the first one in the queue queue.add(start); while(!queue.isEmpty()){ //get the first thing off of the queue //gets the first item and removes it MazePosition current = queue.poll(); //are we done yet? if(current.isFinishState()){ finish = current; break; //exit the loop } //is this something we can test if(current.isUsableState()){ //mark it as visited maze[current.row][current.col] = MARK; //check all of the directions for(int i = 0; i < directions.length; i++){ MazePosition next = new MazePosition( current.row + directions[i][0], current.col + directions[i][1], current.distance + 1, //new distance current); //set the current position as the parent queue.add(next); } } } //end while //add the solution to the maze MazePosition pos = finish; while(pos != null){ maze[pos.row][pos.col] = PATH; pos = pos.parent; } cleanMaze(); //remove marks and restore S and F } class MazePosition implements Comparable{ int row; int col; int distance; MazePosition parent; public MazePosition(int r, int c, int d, MazePosition p){ row = r; col = c; distance = d; parent = p; } @Override public int compareTo(MazePosition arg) { //returns: // < 0 this < arg // > 0 this > arg // == 0 this == arg //the number of steps to get here + // a guess at how many steps we might be from the goal //Breadth First Search //return distance - arg.distance; //Depth First Search //return arg.distance - distance; //Best First Search int thisDist = distance + Math.max(rows-1-row, cols-1-col); int argDist = arg.distance + Math.max(rows-1-arg.row, cols-1-arg.col); return thisDist - argDist; } public boolean isUsableState(){ if(row < 0 || row >= rows || col < 0 || col >=cols) //current position is out of bounds return false; if(maze[row][col] == MARK || maze[row][col] == WALL){ //current position is marked or a wall return false; } return true; } public boolean isFinishState(){ return row == rows - 1 && col == cols -1; } } }