Minimum Knight Moves Problem
Description
LeetCode Problem 1197.
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]
Constraints:
-300 <= x, y <= 3000 <= |x| + |y| <= 300
Solution
Approach: BFS in One Quadrant
Every knight move costs one step, so the fewest moves to (x, y) is a shortest path in an unweighted graph: a breadth-first search from (0, 0) that returns the level at which it reaches the target.
The board is infinite, so we need to keep the search small:
- Symmetry. Flipping the sign of
xorymirrors every knight move, so the answer for(x, y)equals the answer for(|x|, |y|). We only search for a target in the first quadrant. - Do not wander far below the axes. A shortest path to a first-quadrant square never needs to go below
-1in either coordinate, so we drop squares withi < -1orj < -1. The bound must be-1, not0:(1, 1)takes 2 moves,(0, 0) -> (2, -1) -> (1, 1), and this path dips to-1.
Mark squares as seen when they are added to the queue, so each square is queued at most once. Since |x| + |y| <= 300, the answer is at most 150 moves, and no coordinate the search reaches before then goes much beyond 300, so a fixed 700 x 700 array (shifted by one so that -1 fits) is enough for the seen marks.
Complexity: O(d2) time and space, where d = |x| + |y|: the BFS only visits squares within the answer's distance from the origin.
from collections import deque
class Solution:
def minKnightMoves(self, x: int, y: int) -> int:
# The board is symmetric, so solve for the target in the first quadrant.
x, y = abs(x), abs(y)
moves = ((1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2))
seen = {(0, 0)}
queue = deque([(0, 0)])
steps = 0
while queue:
for _ in range(len(queue)):
i, j = queue.popleft()
if i == x and j == y:
return steps
for di, dj in moves:
a, b = i + di, j + dj
# A shortest path never needs to go below -1 (e.g. (0,0) -> (2,-1) -> (1,1)).
if a >= -1 and b >= -1 and (a, b) not in seen:
seen.add((a, b))
queue.append((a, b))
steps += 1
return -1