In an infinite chess board with coordinates from -infinity
to +infinity
, you have a knight at square [0, 0]
.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return the minimum number of steps needed to move the knight to the square [x, y]
. It is guaranteed the answer exists.
Example 1:
Input: x = 2, y = 1 Output: 1 Explanation: [0, 0] → [2, 1]
Example 2:
Input: x = 5, y = 5 Output: 4 Explanation: [0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5]
思路:x,y abs之后,四个象限可以变成求一个象限的step,因为全部对称。注意>= -1, >=-1是因为第一象限(1,1)这个点,是不能reach的,如果可以变成负数,就可以reach,所以这里是特殊情况,我觉得面试的时候,面试官应该提醒这个吧,否则没人知道。
class Solution {
public int minKnightMoves(int x, int y) {
x = Math.abs(x);
y = Math.abs(y);
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0,0});
int[][] dirs = {{2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}};
int step = 0;
HashSet<String> visited = new HashSet<>();
visited.add("0,0");
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
int[] node = queue.poll();
if(node[0] == x && node[1] == y) {
return step;
}
for(int[] dir: dirs) {
int nx = node[0] + dir[0];
int ny = node[1] + dir[1];
if(!visited.contains(nx + "," + ny) && nx >= -1 && ny >= -1) {
visited.add(nx + "," + ny);
queue.offer(new int[] {nx, ny});
}
}
}
step++;
}
return -1;
}
}