Priority Queue simple solution


#1

public class Solution {

public class PointWithMinSteps{
    public int x;
    public int y;
    public int s;
    PointWithMinSteps(int x, int y, int s){
        this.x=x;
        this.y=y;
        this.s=s;
    }
}


public int knight(int A, int B, int C, int D, int E, int F) {
    
    PriorityQueue<PointWithMinSteps>pq = new PriorityQueue<>((a,b)->a.s-b.s);
    if(C==E && D==F){
        return 0;
    }
    int[][] visited = new int[A+1][B+1];
    int[] dirX = {-1,-2,-2,-1,1,2,2,1};
    int[] dirY = {2,1,-1,-2,-2,-1,1,2};
    int count = Integer.MAX_VALUE;
    boolean found=false;
    
    PointWithMinSteps start = new PointWithMinSteps(C,D,0);
    pq.add(start);
    visited[C][D]=1;

    while(!pq.isEmpty()){
        PointWithMinSteps currP = pq.poll();
        for(int i=0; i<8; i++){
            PointWithMinSteps newP = new PointWithMinSteps(currP.x+dirX[i], currP.y+dirY[i], currP.s+1);
            if(newP.x<=0 || newP.y<=0 || newP.x>A || newP.y>B || visited[newP.x][newP.y]==1){
                continue;
            }
            
            if(newP.x==E && newP.y==F){
                return newP.s;
            }
            pq.add(newP);
            visited[newP.x][newP.y]=1;
        }
    }
    
    return -1;
}

}