Minimum Knight Moves
Medium
Topics
On an infinite chessboard with coordinates from -infinity to +infinity, a knight starts at square [0, 0].
A knight has 8 possible moves: it moves two squares in one cardinal direction and then one square in a perpendicular direction.
Return the minimum number of moves needed to reach the square [a, b]. It is always possible.
The target is named a and b here because that is what the judge calls the two arguments; LeetCode calls them x and y.
Example 1
Input: a = 2, b = 1 Output: 1 Explanation: A single knight move reaches [2,1] from the origin.
Example 2
(5, 5) takes 4 moves.Input: a = 5, b = 5 Output: 4 Explanation: No three moves reach [5,5]; four do.
Example 3
Input: a = 0, b = 0 Output: 0 Explanation: The knight is already there.
Example 4
Input: a = 1, b = 1 Output: 2 Explanation: A diagonal neighbour is two moves away, not one — the knight cannot step diagonally.
Constraints
- -300 <= a, b <= 300
- 0 <= |a| + |b| <= 300
Editorial — intuition, approach, complexity and pitfalls
Intuition
Every move costs the same, so the shortest sequence is a shortest path in an unweighted graph whose vertices are squares. On an infinite board the graph is infinite, which is the only real obstacle — the search has to be fenced in somehow.
Two observations do the fencing. The board is symmetric under reflection in both axes and under swapping the axes, so a target in any quadrant can be folded into the first by taking absolute values; the answer is unchanged. And a shortest path never needs to wander far outside the rectangle between the origin and the target — a small margin is enough, because any excursion further out has to be walked back.
With a bounded region the search is an ordinary breadth-first expansion, which is what guarantees the minimum: squares are reached in order of distance, so the first time the target is dequeued is on a shortest path.
Approach
- Fold the target into the first quadrant by taking absolute values of both coordinates. Reflections do not change the move count.
- Breadth-first search from
(0, 0), expanding all 8 knight moves from each square. - Confine the search to squares with both coordinates between
-2and the target coordinate plus 2. The margin allows the small overshoot that near-axis targets need — reaching(1, 1)requires stepping to a negative coordinate or past the target. - Mark squares as seen when enqueued, not when dequeued, so no square joins the frontier twice.
- Return the distance recorded when the target is first reached.
Walkthrough
a = 1, b = 1 (already in the first quadrant)
search box: -2 .. 3 on both axes
distance 0 (0,0)
distance 1 the eight moves from the origin
(2,1) (1,2) (-1,2) (-2,1) (-2,-1) (-1,-2) (1,-2) (2,-1)
the target is not among them
distance 2 expanding that frontier, one square reaches it:
from (-1,2) by (+2,-1) -> (1,1) found
answer 2
The only two-move routes to (1,1) pass through a square with a
negative coordinate, which is why the box extends to -2 rather
than stopping at the origin.Complexity
- Time — O(a * b): the search visits each square of the bounded box at most once, and the box is proportional to the target coordinates.
- Space — O(a * b): the seen set and the queue, both bounded by the box.
Common Pitfalls
- Searching the unbounded board. Without a box the frontier grows for ever on an unreachable-looking target, and even on a reachable one it explores far more squares than it needs.
- Making the box exactly the rectangle from the origin to the target. Targets near an axis need to step outside it —
(1, 1)is unreachable without visiting a negative coordinate — so the answer comes back wrong or not at all. - Marking a square seen when it is dequeued rather than when it is enqueued. The same square then enters the queue from several neighbours, which is correct but much slower.
- Trying a greedy or closed-form rule based on
|a| + |b|. It works for most targets and fails on the small ones near the origin and the axes, which is exactly where the test cases concentrate.
Full Solution — all languages
class Solution:
def minKnightMoves(self, a, b):
from collections import deque
x, y = abs(a), abs(b)
if x == 0 and y == 0:
return 0
MOVES = ((1, 2), (2, 1), (2, -1), (1, -2),
(-1, -2), (-2, -1), (-2, 1), (-1, 2))
seen = {(0, 0)}
q = deque([(0, 0, 0)])
while q:
cx, cy, steps = q.popleft()
if cx == x and cy == y:
return steps
for dx, dy in MOVES:
nx, ny = cx + dx, cy + dy
if -2 <= nx <= x + 2 and -2 <= ny <= y + 2 and (nx, ny) not in seen:
seen.add((nx, ny))
q.append((nx, ny, steps + 1))
return -1import java.util.*;
class Solution {
public int minKnightMoves(int a, int b) {
int x = Math.abs(a), y = Math.abs(b);
if (x == 0 && y == 0) return 0;
int[][] MOVES = { {
1, 2
},
{
2, 1
},
{
2, -1
},
{
1, -2
},
{
-1, -2
},
{
-2, -1
},
{
-2, 1
},
{
-1, 2
}
};
int H = y + 5;
boolean[] seen = new boolean[(x + 5) * H];
Deque<int[]> q = new ArrayDeque<>();
q.add(new int[]{0, 0, 0});
seen[2 * H + 2] = true;
while (!q.isEmpty()) {
int[] cur = q.poll();
if (cur[0] == x && cur[1] == y) return cur[2];
for (int[] m : MOVES) {
int nx = cur[0] + m[0], ny = cur[1] + m[1];
if (nx < -2 || nx > x + 2 || ny < -2 || ny > y + 2) continue;
int idx = (nx + 2) * H + (ny + 2);
if (seen[idx]) continue;
seen[idx] = true;
q.add(new int[]{nx, ny, cur[2] + 1});
}
}
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minKnightMoves(int a, int b) {
int x = abs(a), y = abs(b);
if (x == 0 && y == 0) return 0;
int MOVES[8][2] = { {
1, 2
},
{
2, 1
},
{
2, -1
},
{
1, -2
},
{
-1, -2
},
{
-2, -1
},
{
-2, 1
},
{
-1, 2
}
};
int W = x + 5, H = y + 5;
vector<char> seen((size_t)W * H, 0);
auto at = [&](int px, int py) {
return (size_t)(px + 2) * H + (py + 2);
};
queue<array<int, 3>> q;
q.push({0, 0, 0});
seen[at(0, 0)] = 1;
while (!q.empty()) {
array<int, 3> cur = q.front();
q.pop();
if (cur[0] == x && cur[1] == y) return cur[2];
for (auto& m : MOVES) {
int nx = cur[0] + m[0], ny = cur[1] + m[1];
if (nx < -2 || nx > x + 2 || ny < -2 || ny > y + 2) continue;
if (seen[at(nx, ny)]) continue;
seen[at(nx, ny)] = 1;
q.push({nx, ny, cur[2] + 1});
}
}
return -1;
}
};/**
* @param {number} a
* @param {number} b
* @return {number}
*/ var minKnightMoves = function(a, b) {
const x = Math.abs(a), y = Math.abs(b);
if (x === 0 && y === 0) return 0;
const MOVES = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]];
const seen = new Set(['0,0']);
const q = [[0, 0, 0]];
for (let head = 0; head < q.length; head++) {
const cx = q[head][0], cy = q[head][1], steps = q[head][2];
if (cx === x && cy === y) return steps;
for (const m of MOVES) {
const nx = cx + m[0], ny = cy + m[1];
if (nx < -2 || nx > x + 2 || ny < -2 || ny > y + 2) continue;
const key = nx + ',' + ny;
if (seen.has(key)) continue;
seen.add(key);
q.push([nx, ny, steps + 1]);
}
}
return -1;
};