Leetcode #1197: Minimum Knight Moves
In this guide, we solve Leetcode #1197 Minimum Knight Moves in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Breadth-First Search
Intuition
We need level-by-level exploration or shortest steps, which is ideal for BFS.
A queue naturally models the frontier of the search.
Approach
Push initial nodes into a queue and expand in layers.
Track visited nodes to prevent cycles.
Steps:
- Initialize queue with start nodes.
- Process level by level.
- Track visited nodes.
Example
Input: x = 2, y = 1
Output: 1
Explanation: [0, 0] → [2, 1]
Python Solution
class Solution:
def minKnightMoves(self, x: int, y: int) -> int:
q = deque([(0, 0)])
ans = 0
vis = {(0, 0)}
dirs = ((-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1))
while q:
for _ in range(len(q)):
i, j = q.popleft()
if (i, j) == (x, y):
return ans
for a, b in dirs:
c, d = i + a, j + b
if (c, d) not in vis:
vis.add((c, d))
q.append((c, d))
ans += 1
return -1
Complexity
The time complexity is O(V+E). The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.