Show problems as
Classic problem #1197MediumBreadth-First SearchHeuristic SearchBidirectional SearchA* Search

Minimum Knight Moves

Real-world version: Survey Drone L-Hops
Tracked in this browser only
Read Minimum Knight Moves on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A survey drone parks on an unbounded grid of landing pads, at pad (0, 0). Rows and columns run forever in both directions, so pad coordinates may be negative.

One hop takes the drone from pad (a, b) to any pad that is two rows and one column away, or one row and two columns away: the eight pads (a +- 1, b +- 2) and (a +- 2, b +- 1). There are no obstacles, and the drone may hop to pads outside the rectangle between its parking pad and its target.

Given a target pad (x, y), return the fewest hops that land the drone exactly on it. The target is always reachable.

Examples

Example 1

Input
x = 2, y = 1
Output
1

Pad (2, 1) is two rows and one column from the parking pad, so a single hop lands on it.

Example 2

Input
x = 3, y = 3
Output
2

The route (0, 0) to (1, 2) to (3, 3) uses two legal hops and finishes on the target.

Example 3

Input
x = -1, y = -1
Output
2

The route (0, 0) to (-2, 1) to (-1, -1) uses two legal hops and lands on the target.

Constraints

  • -300 <= x, y <= 300
  • |x| + |y| <= 300

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def min_knight_moves(x: int, y: int) -> int:
Java
public int minKnightMoves(int x, int y)