1197.Minimum Knight Moves
Problem description:
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:
1 | Input: x = 2, y = 1 |
Example 2:
1 | Input: x = 5, y = 5 |
Constraints:
300 <= x, y <= 300
0 <= |x| + |y| <= 300
Solution:
Regular BFS
However, since the matrix is symmetric, we could downgrade the destination (x,y)
.
Once the (x,y)
is smaller, then we use BFS to compute
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: