This problem asks for the minimum number of moves a knight needs to reach a target position (x, y) from (0, 0) on an infinite chessboard. We can efficiently solve this using Breadth-First Search (BFS) or Bidirectional BFS.
This approach explores the chessboard level by level, starting from (0, 0). It uses a queue to manage the nodes to visit and a set to track visited nodes to avoid cycles.
Algorithm:
Time Complexity: O(N), where N is the number of nodes visited. In the worst case, this is proportional to the distance from (0,0) to (x,y). Since the search space is restricted, this is practically efficient. Space Complexity: O(N), to store the queue and the visited set.
This approach simultaneously explores from both the starting point (0, 0) and the target point (x, y). It meets in the middle, significantly reducing the search space for faraway targets.
Algorithm:
q1
(starting from (0, 0)) and q2
(starting from (x, y)). Two hash maps (m1
, m2
) store visited nodes and their distances from their respective start points.Time Complexity: O(sqrt(N)) on average, where N is the number of nodes in a single-directional BFS. This is a significant improvement over single-directional BFS for distant targets. Space Complexity: O(sqrt(N)), for the two queues and visited sets.
Approach 1 (BFS):
from collections import deque
class Solution:
def minKnightMoves(self, x: int, y: int) -> int:
q = deque([(0, 0, 0)]) # (x, y, steps)
visited = {(0, 0)}
while q:
curr_x, curr_y, steps = q.popleft()
if curr_x == x and curr_y == y:
return steps
for dx, dy in [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]:
next_x, next_y = curr_x + dx, curr_y + dy
if (next_x, next_y) not in visited:
visited.add((next_x, next_y))
q.append((next_x, next_y, steps + 1))
Approach 2 (Bidirectional BFS): (More complex; refer to the provided solution for a complete implementation). The core idea is outlined in the algorithm description above.
The Bidirectional BFS approach generally offers superior performance, especially for larger input values of x
and y
, because it explores the search space more efficiently. The single-source BFS, while simpler to implement, can become noticeably slower for distant targets.