Find the fewest knight moves to a square on an infinite chessboard
Problem
A knight moves two squares in one direction and one square at right angles: eight possible moves. On an infinite chessboard, starting at (0, 0), write minKnightMoves(x, y), which returns the fewest moves needed to land on (x, y).
minKnightMoves(2, 1); // 1
minKnightMoves(5, 5); // 4
minKnightMoves(1, 0); // 3
minKnightMoves(0, 0); // 0
minKnightMoves(-1, -2); // 1Ref. UR-1426 · © UIRound · uiround.com/questions/find-the-fewest-knight-moves-to-a-square-on-an-infinite-chessboard
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 4
- edge cases
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Every move costs the same, so breadth-first search from (0, 0) finds the fewest moves: the first time BFS reaches the target, it has used the fewest steps.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.