public class Solution {
boolean board[][];
int nodes_left_in_layer;
int nodes_in_next = 0;
int xcords[] = {-1,-2,-1,2,-2,1,1,2};
int ycords[] = {-2,-1,2,-1,1,-2,2,1};
public boolean check(int x,int y,int A,int B){
if(x < 0 || y < 0 || x>=A || y>=B || board[x][y] == true) return false;
return true;
}
public int knight(int A, int B, int C, int D, int E, int F) {
int count = 0;
Queue<Integer> qx = new LinkedList<>();
Queue<Integer> qy = new LinkedList<>();
board = new boolean[A][B];
C--;
D--;
E--;
F--;
qx.add(C);
qy.add(D);
board[C][D] = true;
nodes_left_in_layer = 1;
int flag = 0;
while(qx.size() != 0){
int x = qx.poll();
int y = qy.poll();
if(x == E && y == F){
// System.out.println("--");
flag = 1;
break;
}
for(int i=0;i<xcords.length;i++){
int xx = x + xcords[i];
int yy = y + ycords[i];
if(check(xx,yy,A,B)){
qx.add(xx);
qy.add(yy);
board[xx][yy] = true;
nodes_in_next++;
}
}
nodes_left_in_layer--;
if(nodes_left_in_layer == 0){
nodes_left_in_layer = nodes_in_next;
nodes_in_next = 0;
count++;
}
}
if(flag == 1){
return count;
}
else{
return -1;
}
}
}
[JAVA] Super Easy (Dont read the editorial, this is way easy)
rahul-mistry
#1