Java Easy solution using bfs


#1
public class Solution {
    class Pair{
        int x,y,count;
        Pair(int x,int y,int count){
            this.x=x;
            this.y=y;
            this.count=count;
        }
    }
    int []shiftX = new int[]{-2, -2, 1, -1, 2, 2, -1, 1};
    int shiftY[] = new int[]{-1, 1, 2, 2, 1, -1, -2, -2};
    boolean valid(int i,int j,int row,int col,boolean[][]visit){
        if(i>0 && i<=row && j>0 && j<=col && !visit[i][j]) return true;
        return false;
    }
    public int knight(int matrixRow, int matrixCol, int startX, int startY, int endX, int endY) {
        Queue<Pair> q  =new LinkedList<>();
        q.offer(new Pair(startX,startY,0));
        boolean visit[][] = new boolean[matrixRow+1][matrixCol+1];
        visit[startX][startY]=true;
        while(!q.isEmpty()){
            Pair  p = q.remove();
            int x=p.x;
            int y=p.y;
            int count=p.count;
            if(x==endX && y==endY){
                return count;
            }
            for(int i=0;i<8;i++){
                int nx=x+shiftX[i];
                int ny=y+shiftY[i];
                if(valid(nx,ny,matrixRow,matrixCol,visit)){
                    visit[nx][ny]=true;
                    q.offer(new Pair(nx,ny,count+1));
                }
            }
        }
        return -1;
    }
}