private boolean isValid(int x, int y, Set<String> visited) {
return x >= -2 && y >= -2 && !visited.contains(x + "," + y);
}
class Solution {
private static final int[][] DIRS = {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
public int minKnightMoves(int x, int y) {
x = Math.abs(x);
y = Math.abs(y);
Set<String> visited = new HashSet<>();
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0});
visited.add(0 + "," + 0);
int steps = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int q = 0; q < size; q++) {
int[] cur = queue.poll();
int curX = cur[0];
int curY = cur[1];
if (curX == x && curY == y) {
return steps;
}
for (int[] dir : DIRS) {
int nextX = curX + dir[0];
int nextY = curY + dir[1];
if (!isValid(nextX, nextY, visited)) {
continue;
}
queue.offer(new int[]{nextX, nextY});
visited.add(nextX + "," + nextY);
}
}
steps++;
}
return -1;
}
private boolean isValid(int x, int y, Set<String> visited) {
return x >= -2 && y >= -2 && !visited.contains(x + "," + y);
}
}ja