Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the minimum number of jumps for a knight to reach a target on an infinite board (BFS).

Problem: Find the minimum number of jumps for a knight to reach a target on an infinite board (BFS).
from collections import deque
def knight(tx, ty):
    tx, ty = abs(tx), abs(ty)
    moves = [(1, 2), (2, 1), (-1, 2), (-2, 1), (1, -2), (2, -1), (-1, -2), (-2, -1)]
    q, seen = deque([(0, 0, 0)]), {(0, 0)}
    while q:
        x, y, d = q.popleft()
        if (x, y) == (tx, ty): return d
        for dx, dy in moves:
            nx, ny = x + dx, y + dy
            if -2 <= nx <= tx + 2 and -2 <= ny <= ty + 2 and (nx, ny) not in seen:
                seen.add((nx, ny)); q.append((nx, ny, d + 1))
print(knight(1, 1), knight(5, 5), knight(0, 1))
What is printed?
  1. A. 2 4 3
  2. B. 2 4 1
  3. C. 4 4 3
  4. D. 2 5 3

Correct answer: A. 2 4 3

BFS on board squares; symmetry lets us fold the target into the first quadrant, and a small margin (−2) is enough because optimal paths never wander far. (1, 1) needs 2 moves, e.g. (2, −1) then (−1, 2); the adjacent square (0, 1) surprisingly needs 3; (5, 5) needs 4. Without the margin, targets like (1, 1) would be unreachable inside the box. O(area) of the bounded box.

More Coding Interview Problems questions

Exams that ask this topic