Talentd
FleetCode

1197. Minimum Knight Moves

Medium41.8% acceptance13 companiesPremium elsewhere, free here

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 <= 300
  • 0 <= |x| + |y| <= 300

Hints open one at a time

Hint 1
You can simulate the movements since the limits are low.
Hint 2
Is there a search algorithm applicable to this problem?
Hint 3
Since we want the minimum number of moves, we can use Breadth First Search.
19:26
Still stuck?Read 2 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
2
1
Input
5
5
Your code is saved on this device.Solution