题目地址:
https://leetcode.com/problems/minimum-knight-moves/
马踏棋盘。设马在 ( 0 , 0 ) (0,0) (0,0)这个位置,再给定一个位置 ( x , y ) (x,y) (x,y),问马至少需要多少步能到 ( x , y ) (x,y) (x,y)。题目保证 ∣ x ∣ + ∣ y ∣ ≤ 300 |x|+|y|\le 300 ∣x∣+∣y∣≤300。
参考https://blog.csdn.net/qq_46105170/article/details/122228447。代码如下:
public class Solution {
public int minKnightMoves(int x, int y) {
if (x == 0 && y == 0) {
return 0;
}
x = Math.abs(x);
y = Math.abs(y);
if (x < y) {
int tmp = x;
x = y;
y = tmp;
}
return f(x, y);
}
int f(int x, int y) {
if (x == 1 && y == 0) {
return 3;
}
if (x == 2 && y == 2) {
return 4;
}
if (y <= x - y) {
if (x % 2 == 0) {
return x / 2 + (x / 2 - y) % 2;
} else {
return (x + 1) / 2 + ((x + 1) / 2 - (y + 1)) % 2;
}
}
int d = (2 * y - x) / 3;
if (d == 0) {
d = 1;
}
x += d;
y -= d;
return f(x, y);
}
}
时空复杂度 O ( 1 ) O(1) O(1)。