694. Knight's Shortest Trip

Medium3.5 points estimatedGraphBreadth-First SearchMaths3 hints

A chess knight stands on the square (0, 0) of an endless board whose squares are addressed by integer coordinates. It moves in any of the eight usual L-shaped ways: two squares along one axis and one square along the other. Given a destination (x, y), return the smallest number of knight moves needed to land on it.

The board has no edges, so a route may pass through negative coordinates, although a shortest route never needs to stray far from the straight line between the two squares. Every square is reachable. A breadth-first search inside a bounded window around the origin, together with the mirror symmetry of the board, answers each query in roughly O(|x| * |y|) time.

Example 1

Input:
x = 4, y = 7
Output:
5
Explanation:

The knight needs 5 moves to reach (4, 7); no shorter combination of L-shaped moves lands on that square.

Example 2

Input:
x = -6, y = -9
Output:
5
Explanation:

By symmetry (-6, -9) takes as many moves as (6, 9), which is 5.

Example 3

Input:
x = 3, y = 0
Output:
3
Explanation:

Three moves reach (3, 0): (0, 0) to (2, 1), then to (1, -1), then to (3, 0). One or two moves cannot land on that square.

Constraints

-300 ≤ x, y ≤ 300

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(|x| * |y|)
Space
O(|x| * |y|)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…